Algorithm
Problem link : https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=973
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 input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs. 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 For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line. 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 1 3 100 90 200
Sample Output 190 200
Code Examples
#1 Code Example with C Programming
Code -
C Programming
#include <bits/stdc++.h>
using namespace std;
// knapsack/subset sum trick when n < =64, we can use bitmask
int main()
{
int tc,n,v;
scanf("%d",&tc);
while(tc--){
scanf("%d",&n);
int sum=0;
vector<int> weights;
for(int i=0;i < n;i++){
scanf("%d",&v);
weights.push_back(v);
sum+=v;
}
int half_sum = sum/2;
int half_ppl = n/2;
// dp bitmask, each bit i representing whether i people can form it
vector < long long> dp(half_sum+1);
dp[0]=1;
for(int i=0;i < n;i++)
for(int j=half_sum;j>=weights[i];j--)
dp[j] |= (dp[j-weights[i]] << 1LL); // shift one as dp[n][j] |= dp[n-1][j-weights[i]]
int best=-1;
for(int i=half_sum;i>=0&&best==-1;i--){
if(dp[i] & (1LL i&It half_ppl)) best=i;
else if(n%2 && dp[i] & (1LL i&It (half_ppl+1))) best=i;
}
printf("%d %d\n",best,sum-best);
if(tc) printf("\n");
}
}
Copy The Code &
Try With Live Editor
Input
3
100
90
200
Output
Demonstration
UVA Online Judge solution - 10032 - Tug of War - UVA online judge solution in C,C++,Java