PAT 甲级 1113  Integer Set Partition

本文探讨了一种将正整数集合划分为两个子集的方法,旨在最小化子集元素数量的差值,并最大化子集元素总和的差值。通过排序和累加策略,实现了高效算法,对比了不同实现方式的性能差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1113 Integer Set Partition (25 point(s))

Given a set of N (>1) 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 ∣n​1​​−n​2​​∣ is minimized first, and then ∣S​1​​−S​2​​∣ is maximized.

Input Specification:

Each input file contains one test case. For each case, the first line gives an integer N (2≤N≤10​5​​), 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: ∣n​1​​−n​2​​∣ and ∣S​1​​−S​2​​∣, 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

经验总结:

emmmm 这一题让我想起了408DS的算法大题,应该是一模一样,不过,当我把书上答案原封不动的码下来提交之后,第四个测试点竟然超时。。。。百思不得其解,遂弃之,直接排序,累加总和,然后输出,比书上的简单还快,舒服~
附上书上的实现代码(无法AC)哪位大佬如果可以AC的话,还请评论里指教一番~

AC代码

#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn=100010;
int n,d[maxn];
int main()
{
	scanf("%d",&n);
	int sum=0,s1=0;
	for(int i=0;i<n;++i)
	{
		scanf("%d",&d[i]);
		sum+=d[i];
	}
	sort(d,d+n);
	for(int i=0;i<n/2;++i)
		s1+=d[i];
	printf("%d %d\n",n%2,sum-s1-s1);
	return 0;
}

附:书上408结构算法题答案代码:

#include <cstdio>
#include <cstring>
const int maxn=100010;
int n,d[maxn];
int main()
{
	scanf("%d",&n);
	int sum=0;
	for(int i=0;i<n;++i)
	{
		scanf("%d",&d[i]);
		sum+=d[i];
	}
	int low=0,high=n-1,k=n/2,low0=0,high0=n-1,flag=1;
	while(flag)
	{
		int pivot=d[low];
		while(low<high)
		{
			while(low<high&&d[high]>=pivot) --high;
			if(low!=high)	d[low]=d[high];
			while(low<high&&d[low]<=pivot) ++low;
			if(low!=high)	d[high]=d[low];
		}
		d[low]=pivot;
		if(low==k-1)
			flag=0;
		else
		{
			if(low<k-1)
			{
				++low;
				low0=low;
				high=high0;
			}
			else
			{
				--high;
				high0=high;
				low=low0;
			}
		}
	}
	int s1=0,s2=0;
	for(int i=0;i<k;++i)
		s1+=d[i];
	printf("%d %d\n",n%2,sum-s1-s1);
	return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值