Align AtCoder - 4371
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
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
6 3 1 4 1 5 9
Sample Output
25
Sample Input
3 5 5 1
Sample Output
8
题意:对于原序列进行排序,找到一种排序方法,使得相邻两个数字的差值的绝对值的和最大。
解题思路:将序列从小大到达排序,取后面一般的数列 减去 前面一半的数列 可以得到一个最大差值
分奇数情况 和 偶数情况讨论 (叫前面一半的数列的元素为较小数, 后面一半数列的的元素为较大数)
奇数情况:假设序列的排序情况只有 大小大小大 或者 小大小大小 两种形式 较大数和较小数较差排列
大小大小大情况 : 两端都少加了一次
小大小大小情况 : 两端都少减了一次
偶数情况:大小大小 和 小大小大 情况相同
注意:数据范围!!!
#include<stdio.h> #include<string.h> #include<iostream> #include<algorithm> #include<map> #include<string> #include<set> #include<stack> #include<queue> using namespace std; const int maxn = 200000; long long n,ans; long long num[maxn]; int main(){ scanf("%lld",&n); for(int i = 1; i <= n ; i++){ scanf("%lld",&num[i]); } sort(num + 1, num+ n + 1); if(n&1){ long long temp1 = 0,tem1 = 0,ans1 = 0; long long temp2 = 0,tem2 = 0,ans2 = 0; int t1 = n / 2 + 1; for(int i = 1 ;i <= t1 ; i++) temp1 += 2*num[i]; for(int i = t1 + 1 ; i <= n ; i++) tem1 += 2*num[i]; ans1 = tem1 - temp1 + num[t1] + num[t1 - 1]; int t2 = n/2; for(int i = 1 ; i <= t2 ; i++) temp2 += 2*num[i]; for(int i = t2 + 1 ; i <= n ; i++) tem2 += 2*num[i]; ans2 = tem2 - temp2 - num[t2 + 1] - num[t2 + 2]; ans = max(ans1,ans2); }else{ long long t = n/2; long long tem = 0,temp = 0; for(int i = 1 ; i <= t ; i++) temp += 2*num[i]; for(int i = t + 1 ; i <= n ; i++) tem += 2 * num[i]; ans = tem - temp - num[t + 1] + num[t]; } printf("%lld ",ans); return 0; }
一个从很久以前就开始做的梦。