1113. Integer Set Partition (25)
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 555Sample Output 1:
0 3611Sample Input 2:
13 110 79 218 69 3721 100 29 135 2 6 13 5188 85Sample Output 2:
1 935 9
【解析】 此题的意思我一开始什么都没看懂,之后有了翻译嘿嘿,其实这道题的意思很简单就是怎么样可以把这个一个集合分成两个集合使这两个集合的元素个数差最小,并且使两个集 合的差最大,看到这里其实就是一个排序算法,如果有n个元素并且n是偶数则这两个集合就没有元素个数差又保证了两个集合的差最大,如果n是奇数,个数差是1个,也满足 了条件。这里计算一下元素总和再计算一下n/2的总和就可以求出了。
#include<iostream> #include<string> #include<algorithm> using namespace std; int main() { int n,m,k,i,sum1=0,sum2=0; cin>>n; int a[n]; for(i=0;i<n;i++) { cin>>a[i]; sum1=sum1+a[i]; } sort(a,a+n); for(i=0;i<n/2;i++) { sum2=sum2+a[i]; } cout<<n%2<<" "<<sum1-(2*sum2)<<endl; return 0; }