cut (sort summation)

Topic: Cut

I am the subject portal! !

Title Description

To give you a sequence of length n, each time you may be divided into a sequence of two consecutive sub-sequences,
the cost is the sum divided prosequence.
Now it allows you to rearrange the time when the initial sequence.
Q is divided into n sequences of length 1 maximum total consideration is how much?

Enter a description:

The first line of a number n represents the length of the original sequence;
next line number n i represents the number of a_i prosequence.
2 <= n-<= 100000
0 <= a_i <= 10000

Output Description:

A row of integer answer.

Example 1

Input
. 4
. 3. 4 2 1
Output
26
described
[3,2,4,1] Rearrangement -> [1,2,3,4] -> [1], [2,3,4] -> [1], [2], [3,4] -> [1], [2], [3], [4].

Example 2

Input
. 4
. 1. 1. 1. 1
output
9


Problem Solving : Sort sum


python:

Code length: 140 Run Time: 182 ms memory for: 14916K

n=int(input())
l=[int(x) for x in input().split()]
l.sort()
a=len(l)
sum=0
for i in range(0,a):
    sum+=l[i]*(i+1)
sum=sum-l[-1]
print(sum)

Obviously time consuming.


c

Code length: 510 running time: 6 ms take up memory: 376
// because there is time consuming, this time not to run reference

#include<stdio.h>
int main()
{
    int a[10000];
    int n,sum=0;
    scanf("%d",&n);
    for(int i=0;i<n;i++)scanf("%d",&a[i]);
    for(int j=0;j<n-1;j++)
    {
        for(int k=0;k<n-j-1;k++)
        {
            if (a[k]>a[k+1])
            {
                 int temp=a[k];
                 a[k]=a[k+1];
                 a[k+1]=temp;
            }
        }
    }
    for(int h=0;h<n;h++) sum+=a[h]*(h+1);
    sum=sum-a[n-1];
    printf("%d",sum);
    return 0;
}

Two-cycle, time consuming


c++

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int n;
    cin>>n;
    int a[100008];
    long long sum=0;
    for(int i=0;i<n;i++)
    {
        cin>>a[i];
    }
    sort(a,a+n);
    for(int i=0;i<n;i++)
    {
        sum+=a[i]*(i+1);
    }
    cout<<sum-a[n-1]<<endl;
    return 0;
}

C ++ using the sort function to solve the embarrassing two-cycle.


over。

Guess you like

Origin blog.csdn.net/qq_42906486/article/details/86556489
cut