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)
  • 相关阅读:
    Selenium
    Selenium和ChromeDriver下载地址
    CQRS Event Sourcing介绍
    JAVA程序员面试30问(附带答案)
    拼多多、饿了么、蚂蚁金服Java面试题大集合
    40K刚面完Java岗,这些技术必须掌握
    接口测试之深入理解HTTPS
    选择了软件测试,你后悔吗?
    如何优雅的使用 Python 实现文件递归遍历
    刚从阿里回来,有些想法想跟测试员说说
  • 原文地址:https://www.cnblogs.com/h-hkai/p/12774208.html
Copyright © 2011-2022 走看看