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 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
经验总结:
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;
}