[Network] cattle off cattle off the winter training camp 1-- basic algorithm with a small "204"

Links: https://ac.nowcoder.com/acm/contest/317/B
Source: Cattle-off network
 

Time limit: C / C ++ 1 second, 2 seconds languages other
space restrictions: C / C ++ 262144K, other languages 524288K
64bit the IO the Format: LLD%

Title Description

A very small like this number 204204, because 'a' + 'k' = 204'a '+' k '= 204.
Now he has a sequence length nn, wherein 2,0,42,0,4 contains only these three figures
is provided for the first ii aiai sequence number, you need to rearrange the columns, such Σni = 1 (ai -ai-1) 2Σi = 1n ( ai-ai-1) meaning 2 maximum (formula is: number per square front and a difference number)
Note: we default a0 = 0a0 = 0

Enter a description:

第一行一个整数nn
接下来一行nn个整数,第ii个数表示aiai

Output Description:

输出一个整数,表示∑ni=1(ai−ai−1)2∑i=1n(ai−ai−1)2的最大值

Example 1

Entry

copy

2
2 4

Export

copy

20

Explanation

样例1解释:按(4,2)(4,2)排列是最优的,此时sum=(4−0)2+(2−4)2=20sum=(4−0)2+(2−4)2=20

Example 2

Entry

copy

3
2 0 4

Export

copy

36

Explanation

样例2解释:按(4,0,2)(4,0,2)排列是最优的,此时sum=(4−0)2+(0−4)2+(2−0)2=36sum=(4−0)2+(0−4)2+(2−0)2=36

Example 3

Entry

copy

5 
2 4 0 2 4

Export

copy

52

Remarks:

1⩽n⩽1051⩽n⩽105,保证aiai为2/0/42/0/4中的数

answer:

The maximum conditions: maximum, minimum, maximum, minimum, maximum, minimum .......

First, sort the array, followed by two pointers i, j are the beginning and end points. To the new array elements one by one according to the minimum, the maximum and then added sequentially. Until the two meet pointer. Arranging sequence has been optimized, scan it again to get ans.

AC Code:

#include<bits/stdc++.h>
using namespace std;
int a[100010],b[100010];
int main()
{
    int n;
    cin>>n;
    a[0]=0;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    sort(a,a+1+n);
    int i=0,j=n,k=0;
    while(i<=j)
    {
        if(k%2==0)
            b[k++]=a[i++];
        else
            b[k++]=a[j--];
    }
     
    long long int ans=0;
    for(i=1;i<=n;i++)
    {
        ans+=(b[i]-b[i-1])*(b[i]-b[i-1]);
    }
    cout<<ans<<endl;
    return 0;
}

 

Published 119 original articles · won praise 20 · views 60000 +

Guess you like

Origin blog.csdn.net/qq_40727946/article/details/86634724