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.
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.
For each case, print in a line two numbers: ∣ and ∣, separated by exactly one space.
10
23 8 10 99 46 2333 46 1 666 555
0 3611
13
110 79 218 69 3721 100 29 135 2 6 13 5188 85
1 9359
题意:
将一个给定的数组分成两部分,使两部分元素的个数之差最小,总和之差最大。
思路:
将数组排序,从中间开始划分,前一半的和最小,后一半的和最大,满足题意。
Code:
#include
using namespace std;
int sum(vector
int sum = 0;
for (int i = s; i <= e; ++i) {
sum += v[i];
}
return sum;
}
int main() {
int n;
cin >> n;
vector
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;
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章