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

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
本题题意:
这题就是说给你 n 个数,让它们两两相减,将差值相加,求相加和最小为多少。
解题思路:
要使两两差值最小,将它们进行排序,相邻两个数相减的差值相加一定是最小的。
难过注意:
这道题看着简单,但是有一个大坑,让我WA了好多次 大哭    简直了。题上虽然说n 的数值最大是1000,但是你开数组是得用long long 才行。不说了,看代码。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <string.h>
#include <cmath>
using namespace std;
long long int a[20005];
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
       long long int sum=0;
       for(int i=0; i<2*n; i++)
       {
           scanf("%lld",&a[i]);
       }
       sort(a,a+(2*n));
       for(int i=0; i<2*n; i=i+2)
       {
           sum+=abs(a[i]-a[i+1]);
       }
       cout<<sum<<endl;
    }
    return 0;
}





  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值