Problem B: A simple problem
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 94 Solved: 42
Description
Dreamone has a lovely cat. The cat can comfort you if you are very dejected, she can also play with you if
you are very bored. So Dreamone loves her very much. Of course, you bet, she can also make you trouble if
she wants to be naughty. This time, she comes up with a simple problem for fun, just like this:
She has 2n toys. In her heart, she has used a number to stand for each toy, and for example, the 2n toys are
given like this:
A1、A2、A3、….A2n-1、A2n
She wants to divide them into two groups, where each group contains n toys. So we can use B1、
B2...Bn ,which are all from A1、 A2...A2n ,to stand for Group One ,use C1、 C2….Cn ,which are all from A1、
A2...A2n, to stand for Group Two. The cat wants to know the minimum value S for the expression below:
S=|B1-C1|+|B2-C2|+|B3-C3|+...+|Bn-Cn|
As we know Dreamone is studying MaJiang recently, so he has no time to solve the simply problem. But he
knows the 6th program contest of SWUST is on, so he turns to you for help. Can you help him?
Input
The first line of input will be a positive integer C indicating how many data sets will be included. Each of
the C data sets will contain two parts:The first part contains a number n(1<=n<=100000),and the second
parts contains 2n numbers ,which are A1、 A2、 A2n-1、 A2n (0<=Ai<=1000(1<=i<=2n)),represented 2n toys
Output
For each case, output the minimum value S for answer.
Sample Input
2
1
1 3
2
1 1 1 2
Sample Output
2
1
简单问题咱也不放过。
代码:
#include<iostream>
#include<stdio.h>
#include<algorithm>
#define MAX 100000
using namespace std;
int num[2*MAX+100];
int main()
{
//freopen("B.in","r",stdin);
//freopen("B1.out","w",stdout);
int n,m,i;
long long ans;
scanf("%d",&n);
while(n--)
{
ans=0;
scanf("%d",&m);
for(i=0;i<2*m;i++)
scanf("%d",&num[i]);
sort(num,num+2*m);
for(i=1;i<2*m;i=i+2)
ans=ans+num[i]-num[i-1];
printf("%lld\n",ans);
}
return 0;
}
FROM:暑假训练第三场