Advertisement
Guest User

SubSet sums c++

a guest
Nov 13th, 2013
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <iostream>
  2. #define OFFSET 10000
  3. using namespace std;
  4. int possible[OFFSET + OFFSET];
  5. int main()
  6. {
  7.     int N = 3;
  8.     int nums[] = { 2, 7, -3 };
  9.     int minpos = nums[0];
  10.     int maxpos = nums[0];
  11.     for(int i = 0; i < N; i++)
  12.     {
  13.         int newminpos = minpos, newmaxpos = maxpos;
  14.         int newpossible[OFFSET + OFFSET] = { 0 };
  15.         for(int j = maxpos; j >= minpos; j--) // j = one possible sum
  16.         {
  17.             if (possible[j+OFFSET] == 1) newpossible[j+nums[i]+OFFSET] = 1;
  18.             if (j+nums[i] > newmaxpos) newmaxpos = j+nums[i];
  19.             if (j+nums[i] < newminpos) newminpos = j+nums[i];
  20.         }
  21.         minpos = newminpos;
  22.         maxpos = newmaxpos;
  23.         for(int j = maxpos; j >= minpos; j--)
  24.             if (newpossible[j+OFFSET] == 1)
  25.                 possible[j+OFFSET] = 1;
  26.         if (nums[i] > maxpos) maxpos = nums[i];
  27.         if (nums[i] < minpos) minpos = nums[i];
  28.         possible[nums[i]+OFFSET] = 1;
  29.     }
  30.  
  31.     cout << "Numbers: ";
  32.     for(int i = 0; i < N; i++)
  33.     {
  34.         cout << nums[i] << " ";
  35.     }
  36.     cout << endl;
  37.  
  38.     int S = 6;
  39.  
  40.     if (possible[0+OFFSET]) cout << "Sum 0 is possible" << endl;
  41.     else cout << "Sum 0 is not possible" << endl;
  42.  
  43.     if (possible[S+OFFSET]) cout << "Sum " << S << " is possible" << endl;
  44.     else cout << "Sum " << S << " is not possible" << endl;
  45.  
  46.     cout << "Possible sums:";
  47.     for(int i = minpos; i <= maxpos; i++)
  48.     {
  49.         if (possible[i+OFFSET] == 1) cout << " " << i;
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement