Advertisement
marius7122

Untitled

Feb 20th, 2022
1,028
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <cmath>
  4.  
  5. int main (int argc, char const* argv[])
  6. {
  7.     int n;
  8.     std::cin >> n;
  9.     int difference[n];
  10.     int total = 0;
  11.     for(int i=0;i<n;i++){
  12.         int a,b;
  13.         std::cin>>a >>b;
  14.         difference[i] = std::abs(a-b);
  15.         total += difference[i];
  16.     }
  17.  
  18.     // Find each reachable sum up to total/2.
  19.     int  max = total/2;
  20.     bool arr[max+1] = { true };
  21.     for (int i = 0; i < n; i++) {
  22.         int val = difference[i];
  23.         for (int j = max - val; j >= 0; j--) {
  24.             if (arr[j])
  25.                 arr[j+val] = true;
  26.         }
  27.     }
  28.  
  29.     // Find the max reachable sum.  For that sum, print the difference between
  30.     // one child's sum (i) and the other's (total - i).  Since i is always
  31.     // less than or equal to (total - i), the difference will be total - i - i.
  32.     for (int i = max; i >= 0; i--) {
  33.         if (arr[i]) {
  34.             std::cout << total - i - i << std::endl;
  35.             break;
  36.         }
  37.     }
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement