1113 Integer Set Partition

Posted ruruozhenhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1113 Integer Set Partition相关的知识,希望对你有一定的参考价值。

Given a set of N (>) positive integers, you are supposed to partition them into two disjoint sets A?1?? and A?2?? of n?1?? and n?2?? numbers, respectively. Let S?1?? and S?2?? denote the sums of all the numbers in A?1?? and A?2??, 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 2?31??.

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;
}

 

以上是关于1113 Integer Set Partition的主要内容,如果未能解决你的问题,请参考以下文章

1113 Integer Set Partition (25)

1113 Integer Set Partition

PAT 1113 Integer Set Partition

A1113 | Integer Set Partition (25)

A1113 Integer Set Partition (25分)

A1113 Integer Set Partition (25分)