A1113 Integer Set Partition (25 point(s))

简单题,使 ∣S1−S2∣最小

1. 原文

Given a set of N (>1) positive integers, you are supposed to partition them into two disjoint sets A1 and A2 of n1and n2 numbers, respectively. Let S1 and S2 denote the sums of all the numbers in A1 and A2, respectively. You are supposed to make the partition so that ∣n1−n2∣ is minimized first, and then ∣S1−S2∣ is maximized.

Input Specification:

Each input file contains one test case. For each case, the first line gives an integer N (2≤N≤105), and then Npositive integers follow in the next line, separated by spaces. It is guaranteed that all the integers and their sum are less than 2^31.

output Specification:

For each case, print in a line two numbers: ∣n1−n2∣ and ∣S1−S2∣, separated by exactly one space.

Sample Input 1:

1
2
10
23 8 10 99 46 2333 46 1 666 555

Sample output 1:

1
0 3611

Sample Input 1:

1
2
13
110 79 218 69 3721 100 29 135 2 6 13 5188 85

Sample output 1:

1
1 9359

2. 解析

|n1-n2|最小, |s1-s2|最大 :

数组递增排序,取前n/2部分和

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<cstdio>
#include<algorithm>
using namespace std;
int num[100010]={};
int main()
{
int n;
scanf("%d",&n);
int total=0;
for (int i = 0; i < n; ++i)
{
scanf("%d",&num[i]);
total+=num[i];
}
sort(num,num+n);
int sum=0;
for (int i = 0; i < n/2; ++i)
{
sum+=num[i];
}
if (n%2==0)
{
printf("0 ");
}else{
printf("1 ");
}
printf("%d\n",abs(total-sum-sum));

return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1113/
  • 发布时间: 2019-09-03 12:30
  • 更新时间: 2021-10-29 14:08
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!