|
You will be given n integers <A1A2A3...An>. Find a permutation of these n integers so that summation of the absolute differences between adjacent elements is maximized.
Suppose n = 4 and the given integers are <4 2 1 5>. The permutation <2 5 1 4> yields the maximum summation.
For this permutation sum = abs(2-5) + abs(5-1) + abs(1-4) = 3+4+3 = 10.
Of all the 24 permutations, you won�t get any summation whose value exceeds 10. We will call this value, 10, the elegant permuted sum.
Input
The first line of input is an integer T(T<100) that represents the number of test cases. Each case consists of a line that starts with n(1<n<51) followed by n non-negative integers separated by a single space. None of the elements of the given permutation will exceed 1000.
Output
For each case, output the case number followed by the elegant permuted summation.
Sample Input |
Output for Sample Input |
3 4 4 2 1 5 4 1 1 1 1 2 10 1 |
Case 1: 10 Case 2: 0 Case 3: 9 |
Problem Setter: Sohel Hafiz
Special Thanks: Jane Alam Jan
题目意思很简单。
贪心的策略就是先排序,将最大的和最小的放在中间,然后不断地往两侧放,每次取差值最大的数放。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn = 60;
int n,num[maxn];
int main(){
int ncase,T=1;
cin >> ncase;
while(ncase--){
cin >> n;
for(int i = 0; i < n; i++) scanf("%d",&num[i]);
printf("Case %d: ",T++);
sort(num,num+n);
int ans = num[n-1]-num[0];
int lft = 1,rgt = n-2;
int lftval = num[0],rgtval = num[n-1];
while(lft <= rgt){
int tmp = -1,cur;
if(abs(lftval-num[lft])>tmp){
tmp = abs(lftval-num[lft]);
cur = 0;
}
if(abs(lftval-num[rgt])>tmp){
tmp = abs(lftval-num[rgt]);
cur = 1;
}
if(abs(rgtval-num[lft])>tmp){
tmp = abs(rgtval-num[lft]);
cur = 2;
}
if(abs(rgtval-num[rgt])>tmp){
tmp = abs(rgtval-num[rgt]);
cur = 3;
}
ans += tmp;
if(cur==0){
lftval = num[lft];
lft++;
}
if(cur==1){
lftval = num[rgt];
rgt--;
}
if(cur==2){
rgtval = num[lft];
lft++;
}
if(cur==3){
rgtval = num[rgt];
rgt--;
}
}
printf("%d\n",ans);
}
return 0;
}