Tenka 1 Computer Contest C-Align
Posted lecoz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Tenka 1 Computer Contest C-Align相关的知识,希望对你有一定的参考价值。
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
5 6 8 1 2 3
Sample Output 1
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
6 3 1 4 1 5 9
Sample Output 2
25
Sample Input 3
3 5 5 1
Sample Output 3
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! "); #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 ", mx); #ifdef local fclose(stdin); #endif return 0; }
以上是关于Tenka 1 Computer Contest C-Align的主要内容,如果未能解决你的问题,请参考以下文章
题录Atcoder Tenka1 Programmer Contest 2019
Tenka1 Programmer Contest C - Align
Tenka1 Programmer Contest 2019 D - Three Colors