Advertisement
CloneTrooper1019

UVa 10032 - Tug of War

Dec 15th, 2016
419
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #ifdef _MSC_VER
  2. #define _CRT_SECURE_NO_WARNINGS 1
  3. #endif
  4.  
  5. #include <iostream>
  6. #include <vector>
  7.  
  8. using namespace std;
  9. const long long ONE = 1LL;
  10.  
  11. int nextInt()
  12. {
  13.     int next;
  14.     scanf("%d", &next);
  15.     return next;
  16. }
  17.  
  18. int main()
  19. {
  20.     int numCases = nextInt();
  21.  
  22.     vector<int> weights;
  23.     weights.reserve(450);
  24.  
  25.     while (numCases--)
  26.     {
  27.         int numPeople = nextInt();
  28.         int weightSum = 0;
  29.  
  30.         for (int i = 0; i < numPeople; i++)
  31.         {
  32.             int weight = nextInt();
  33.             weights.push_back(weight);
  34.             weightSum += weight;
  35.         }
  36.  
  37.         int halfSum = weightSum / 2;
  38.         int halfPeople = numPeople / 2;
  39.  
  40.         vector<long long> dp(halfSum + 1);
  41.         dp[0] = 1;
  42.  
  43.         for (int i = 0; i < numPeople; i++)
  44.         {
  45.             int weight = weights[i];
  46.             for (int j = halfSum; j >= weight; j--)
  47.                 dp[j] |= dp[j - weight] << ONE;
  48.         }
  49.  
  50.         bool odd = (numPeople % 2);
  51.         bool sub = true;
  52.        
  53.         while (sub)
  54.         {
  55.             int val = dp[halfSum];
  56.             sub = false;
  57.  
  58.             if (!(val & (ONE << halfPeople)))
  59.                 sub = true;
  60.  
  61.             if (sub && odd && (val & (ONE << (halfPeople + 1))))
  62.                 sub = false;
  63.  
  64.             if (sub) halfSum--;
  65.             else break;
  66.         }
  67.  
  68.         printf("%d %d\n", halfSum, weightSum - halfSum);
  69.         weights.clear();
  70.  
  71.         if (numCases > 0)
  72.             cout << endl;
  73.     }
  74.  
  75.     // release memory
  76.     weights.shrink_to_fit();
  77.  
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement