Random algorithm poj 2576 tug of war

Source: Internet
Author: User
Tug of war
Time limit:3000 Ms   Memory limit:65536 K
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 shoshould 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 }
View code

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.