Tug of War
Description
A tug of war is to be arranged at the local office picnic. For the tug of war, the picnickers must be divided into two teams. Each person must be on one team or the other; the number of people on the two teams must not differ by more than 1; the total weight of the people on each team should be as nearly equal as possible.
Input
The first line of input contains n the number of people at the picnic. n lines follow. The first line gives the weight of person 1; the second the weight of person 2; and so on. Each weight is an integer between 1 and 450. There are at most 100 people at the picnic.
Output
Your output will be a single line containing 2 numbers: the total weight of the people on one team, and the total weight of the people on the other team. If these numbers differ, give the lesser first.
Sample Input 3 100 90 200 Sample Output 190 200 Source |
题目大意:
给一些人,每个人都有一定的重量,让你把他们分成两组,使得两组的重量之差绝对值最小。
解题思路:
可以利用模拟退火算法求解,开始随便把人分成两组。然后进行多次随机,每次分别从两个组中选一个人,比较交换后是否更优,如果更优就交换,否则按照一个递减的概率进行交换,同时每次都更新一下最优情况。最后输出最优情况即可。
关于成功率的证明比较麻烦这里就不写了,总体成功率是很高的。
AC代码:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <set>
using namespace std;
#define mem(a,b) memset((a),(b),sizeof(a))
const int MAXN=100+3;
int save[2][MAXN];
int N;
int main()
{
srand((int)time(NULL));
while(~scanf("%d",&N))
{
int sum1=0,sum2=0;
for(int i=0;i<N/2;++i)//前一半的人放到第一组
{
int tmp;
scanf("%d",&tmp);
save[0][i]=tmp;
sum1+=tmp;
}
for(int i=N/2;i<N;++i)//后一半的人放到第二组
{
int tmp;
scanf("%d",&tmp);
save[1][i-N/2]=tmp;
sum2+=tmp;
}
if(N&1)//对于个数是奇数的情况,补一个0,方便后来的转移
{
++N;
save[0][N/2-1]=0;
}
int the_min=abs(sum1-sum2),ans1=sum1,ans2=sum2;
for(int i=0;i<1000000;++i)//随机1e6次
{
int i1=rand()%(N/2),i2=rand()%(N/2);
if(abs(sum1-sum2)>abs(sum1-save[0][i1]+save[1][i2]-sum2-save[0][i1]+save[1][i2])||rand()%100000<=i/2)//更优或者满足概率
{
sum1=sum1-save[0][i1]+save[1][i2];
sum2=sum2-save[1][i2]+save[0][i1];
swap(save[0][i1],save[1][i2]);
if(the_min>abs(sum1-sum2))//如果是更优,更新答案
{
the_min=abs(sum1-sum2);
ans1=sum1;
ans2=sum2;
}
}
}
if(ans1>ans2)
swap(ans1,ans2);
printf("%d %d\n",ans1,ans2);
}
return 0;
}