Description
Zhu Ge is a very clever boy. One day, he discovered 2*n numbers. He wanted to divide them into n groups, each group contains 2 integers, and minimize the sum of the absolute value of the difference of the numbers in each group.
The problem is too difficult to Zhu Ge, so he turned to you. He hopes you can calculate the minimum of the sum of absolute value of the difference among different division strategies.
Input
There are several test cases.
For each test case, there is an integer n (n < 10,000) at the first line. The second line contains 2*n integers. The input ends up with EOF.
Output
For each test case, output the minimum of sum.
Sample Input
3 10 3 4 5 1 6 5 64 5 63 63 23 63 54 64 3 54
Sample Output
7 42
题意,把这几个数分成两个两个一组,然后每组两个数的差值的绝对值之和最小的情况,其实一般看到这样子的情况基本都是贪心,这个题是个比较简单的贪心
就是先把他们排一下序,然后两两相减在相加,就好了,但是为啥那么多人WA呢,就是这个大坑,要用long long
#include <iostream>
#include <algorithm>
#include <math.h>
long long X[100000];
using namespace std;
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<2*n;i++)
{
cin>>X[i];
}
sort(X,X+2*n);
long long num=0;
for(int i=0;i<n;i++)
{
num+=abs(X[2*i+1]-X[2*i]);
}
cout<<num<<endl;
}
}