首页 > 代码库 > 随机算法 poj 2576 Tug of War
随机算法 poj 2576 Tug of War
Tug of War
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 8187 | Accepted: 2204 |
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
310090200
Sample Output
190 200
1 #include <iostream> 2 #include <string.h> 3 #include <stdio.h> 4 #include <math.h> 5 #include <stdlib.h> 6 #include <time.h> 7 using namespace std; 8 int aabs(int a) 9 {10 if(a>0)return a;11 else return -a;12 }13 int main()14 {15 int n,a[110][2],b1=0,b0=0,sum0=0,sum1=0,cha,i;16 scanf("%d",&n);17 srand((unsigned)time(NULL));18 for(i=0; i<n; i++)19 {20 if(i&1)21 scanf("%d",&a[1][b1]),sum1+=a[1][b1++];22 else scanf("%d",&a[0][b0]),sum0+=a[0][b0++];23 }24 cha=aabs(sum1-sum0);25 n=1000000;26 while(n--)27 {28 int c0=rand()%b0;29 int c1=rand()%b1;30 if(cha>aabs((sum0-a[0][c0]+a[1][c1])-(sum1-a[1][c1]+a[0][c0])))31 {32 sum0=sum0-a[0][c0]+a[1][c1];33 sum1=sum1-a[1][c1]+a[0][c0];34 swap(a[0][c0],a[1][c1]);35 cha=aabs(sum0-sum1);36 }37 }38 if(sum0>sum1)swap(sum0,sum1);39 cout<<sum0<<" "<<sum1<<endl;40 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。