您的位置:首页 > 其它

2017年上海金马五校程序设计竞赛 O : An Easy Problem 贪心

2017-06-03 21:57 375 查看


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
4000
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐