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
题目大意:给你一组数据,让你分成两个集合,集合大小之差尽可能小,俩集合元素累加和之差尽可能大;
分析:
作为编程题,这是一道水题,暴力即可。输入时累加全部和得到sum,然后sort排序,累加前半部分和得到sum1,最终返回两个abs(sum-sum1-sum1)即可。
完整代码:
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,sum=0,sum1=0;
cin>>n;
vector<int>v(n);
for(int i=0;i<n;i++){
cin>>v[i];
sum+=v[i];
}
sort(v.begin(),v.end());
for(int i=0;i<n/2;i++){
sum1+=v[i];
}
if(n%2==0) cout<<"0 "<<abs(sum-sum1-sum1);
else cout<<"1 "<<abs(sum-sum1-sum1);
return 0;
}
这里主要说下如何设计出一种高的划分办法。
算法思想:
将最小的 n/2 个元素放在A1,其余放在A2,分组结果即可满足题意。
仿照快排的划分思想,基于枢纽将n个元素划分为两个集合,根据划分后的枢纽所在位置i分别处理。
1)i=n / 2(向下取整),分组完成,算法结束。
2)i<n / 2,则枢纽之前的元素均属于A1集合,继续对i之后的元素进行划分。
3)i>n / 2, 则枢纽之后的元素均属于A2集合,继续对i之前的元素进行划分。
基于此算法,无需对全部元素进行排序,时间复杂度O(n),空间复杂度O(1)
核心代码实现:
int setPartition(int a[],int n){
int pivotkey,low=0,low0=0,high=n-1,high0=n-1,k=n/2;
bool flag=true;
while(flag){
pivotkey=a[low];
while(low<high){//基于枢纽的划分
while(low<high && a[high]>=a[low]) high--;
a[low]=a[high];
while(low<high && a[low]<=a[high]) low++;
a[high]=a[low];
}
a[low]=pivotkey;//枢纽放在最终位置
if(low==k-1){ //划分成功
flag=false;
}else{
if(low<k-1){//继续划分枢纽以后的集合
low0=++low;
high=high0;
}else{
high0=--high;
low=low0;
}
}
}
int s1=0,s2=0;
for(int i=0;i<k;i++) sum1+=a[i];
for(int i=k;i<n;i++) sum2+=a[i];
return abs(sum1-sum2);
}
That‘s all !