1. 程式人生 > >Tenka 1 Computer Contest C-Align

Tenka 1 Computer Contest C-Align

imu tip andrew stand sele title computer maximum algorithm

C - Align


Time limit : 2sec / Memory limit : 1024MB

Score : 400 points

Problem Statement

You are given N integers; the i-th of them is Ai. Find the maximum possible sum of the absolute differences between the adjacent elements after arranging these integers in a row in any order you like.

Constraints

  • 2≤N≤105
  • 1≤Ai≤109
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A1
:
AN

Output

Print the maximum possible sum of the absolute differences between the adjacent elements after arranging the given integers in a row in any order you like.


Sample Input 1

Copy
5
6
8
1
2
3

Sample Output 1

Copy
21

When the integers are arranged as 3,8,1,6,2, the sum of the absolute differences between the adjacent elements is |3?8|+|8?1|+|1?6|+|6?2|=21. This is the maximum possible sum.


Sample Input 2

Copy
6
3
1
4
1
5
9

Sample Output 2

Copy
25

Sample Input 3

Copy
3
5
5
1

Sample Output 3

Copy
8

題解:分奇數和偶數討論。當為奇數時,一定是中間的兩個數在左右邊(兩種情況)使得結果最大。偶數同理,更好枚舉,只有一種情況。

技術分享圖片
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <stack>
#define ll long long
//#define local

using namespace std;

const int MOD = 1e9+7;
const int inf = 0x3f3f3f3f;
const double PI = acos(-1.0);
const int maxn = 1e5+10;

int main() {
#ifdef local
    if(freopen("/Users/Andrew/Desktop/data.txt", "r", stdin) == NULL) printf("can‘t open this file!\n");
#endif
    
    int n;
    int a[maxn];
    ll mx = 0;
    ll sum[maxn];
    scanf("%d", &n);
    for (int i = 0; i < n; ++i) {
        scanf("%d", a+i);
    }
    sort(a, a+n);
    for (int i = 0; i < n; ++i) {
        if (!i) sum[i] = a[i];
        if (i) sum[i] = sum[i-1]+a[i];
    }
    if (n&1) {
        if (n == 3) {
            mx = max(abs(2*a[2]-a[1]-a[0]), abs(2*a[0]-a[1]-a[2])); //當n=3時,特殊討論一下
        } else {
            //如果是選擇靠左邊的兩個數作為兩個端點,那麽他們一定是小於它們相鄰的數的。
            //同理,如果是選擇靠左邊的兩個數作為兩個端點,那麽他們一定是大於它們相鄰的數的。
            //將需要算兩次的數*2
            mx = max(abs(2*(sum[n-1]-sum[n/2])-2*(sum[n/2-2])-(a[n/2]+a[n/2-1])), abs(2*(sum[n-1]-sum[n/2+1])-2*(sum[n/2-1])+(a[n/2]+a[n/2+1])));
        }
    } else {
        mx = abs(2*(sum[n-1]-sum[n/2])-2*(sum[n/2-2])+abs(a[n/2]-a[n/2-1]));
    }
    printf("%lld\n", mx);
#ifdef local
    fclose(stdin);
#endif
    return 0;
}
View Code





Tenka 1 Computer Contest C-Align