✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1113 Integer Set Partition (pintia.cn)
🔑中文翻译:整数集合划分
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪
1113 Integer Set Partition
Given a set of N (>1) positive integers, you are supposed to partition them into two disjoint sets A1 and A2 of n1 and 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 N positive integers follow in the next line, separated by spaces. It is guaranteed that all the integers and their sum are less than 231.
Output Specification:
For each case, print in a line two numbers: ∣n1−n2∣ and ∣S1−S2∣, separated by exactly one space.
Sample Input 1:
10 23 8 10 99 46 2333 46 1 666 555
Sample Output 1:
0 3611
Sample Input 2:
13 110 79 218 69 3721 100 29 135 2 6 13 5188 85
Sample Output 2:
1 9359
题意
给定 n
个数,将这 n
个数划分成两个集合 A1
和 A2
,其中 A1
包含 n1
个数且这些数之和为 s1
,A2
包含 n2
个数且这些数之和为 s2
。
现在需要我们使 |n2-n1|
的值尽可能的小,且 |s2-s1|
的值尽可能的大。
思路
直接上结论,我们只要将数组先排个序,然后尽可能均匀的分成两部分,所以 |n2-n1|
的值只可能为 0
或 1
,且左半部分的值都是小于右半部分的,这样就能使 |s2-s1|
的值最大。
代码
#include<bits/stdc++.h>
using namespace std;const int N = 100010;
int w[N];
int n;int main()
{cin >> n;for (int i = 0; i < n; i++) cin >> w[i];//进行排序sort(w, w + n);//计算两部分数值的和int s1 = 0, s2 = 0;for (int i = 0; i < n / 2; i++) s1 += w[i];for (int i = n / 2; i < n; i++) s2 += w[i];//输出结果cout << n % 2 << " " << s2 - s1 << endl;return 0;
}