【PAT甲级 - C++题解】1113 Integer Set Partition

✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1113 Integer Set Partition (pintia.cn)
🔑中文翻译:整数集合划分
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪

1113 Integer Set Partition

Given a set of N (>1) 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 ∣n1−n2∣ is minimized first, and then ∣S1−S2∣ is maximized.

Input Specification:

Each input file contains one test case. For each case, the first line gives an integer N (2≤N≤105), 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: ∣n1−n2∣ and ∣S1−S2∣, 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
题意

给定 n 个数,将这 n 个数划分成两个集合 A1A2 ,其中 A1 包含 n1 个数且这些数之和为 s1A2 包含 n2 个数且这些数之和为 s2

现在需要我们使 |n2-n1| 的值尽可能的小,且 |s2-s1| 的值尽可能的大。

思路

直接上结论,我们只要将数组先排个序,然后尽可能均匀的分成两部分,所以 |n2-n1| 的值只可能为 01 ,且左半部分的值都是小于右半部分的,这样就能使 |s2-s1| 的值最大。

代码
#include<bits/stdc++.h>
using namespace std;

const int N = 100010;
int w[N];
int n;

int main()
{
    cin >> n;
    for (int i = 0; i < n; i++)    cin >> w[i];

    //进行排序
    sort(w, w + n);

    //计算两部分数值的和
    int s1 = 0, s2 = 0;
    for (int i = 0; i < n / 2; i++)  s1 += w[i];
    for (int i = n / 2; i < n; i++)  s2 += w[i];

    //输出结果
    cout << n % 2 << " " << s2 - s1 << endl;

    return 0;
}
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值