zoukankan      html  css  js  c++  java
  • 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;
    }
    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    < java.util >-- Set接口
    Codeforces 627 A. XOR Equation (数学)
    Codeforces 161 B. Discounts (贪心)
    Codeforces 161 D. Distance in Tree (树dp)
    HDU 5534 Partial Tree (完全背包变形)
    HDU 5927 Auxiliary Set (dfs)
    Codeforces 27E. Number With The Given Amount Of Divisors (暴力)
    lght oj 1257
    Codeforces 219D. Choosing Capital for Treeland (树dp)
    Codeforces 479E. Riding in a Lift (dp + 前缀和优化)
  • 原文地址:https://www.cnblogs.com/h-hkai/p/12774208.html
Copyright © 2011-2022 走看看