1113 Integer Set Partition
作者:互联网
Given a set of N (>) 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 ∣ is minimized first, and then ∣ is maximized.
Input Specification:
Each input file contains one test case. For each case, the first line gives an integer N (2), 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: ∣ and ∣, 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
题意:
将一个给定的数组分成两部分,使两部分元素的个数之差最小,总和之差最大。
思路:
将数组排序,从中间开始划分,前一半的和最小,后一半的和最大,满足题意。
Code:
#include <bits/stdc++.h> using namespace std; int sum(vector<int> v, int s, int e) { int sum = 0; for (int i = s; i <= e; ++i) { sum += v[i]; } return sum; } int main() { int n; cin >> n; vector<int> v(n); for (int i = 0; i < n; ++i) cin >> v[i]; sort(v.begin(), v.end()); int mid = n / 2; int preSum = sum(v, 0, mid - 1); int postSum = sum(v, mid, n - 1); if (v.size() % 2 == 0) { cout << 0 << " " << postSum - preSum << endl; } else { cout << 1 << " " << postSum - preSum << endl; } return 0; }
标签:integers,Set,int,sum,Sample,1113,Input,Integer,line 来源: https://www.cnblogs.com/ruruozhenhao/p/12774208.html