document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. using namespace std;
  2.  
  3. #include<iostream>
  4. #include<cmath>
  5. #include<set>
  6.  
  7. int * binary;
  8.  
  9. void generateBinary(int, int);
  10.  
  11. int main(void)
  12. {
  13.     int n;
  14.     cin >> n;
  15.     int weight[n];
  16.     int sum = 0;
  17.    
  18.     for(int i=0; i<n; i++)
  19.     {
  20.         cin >> weight[i];
  21.         sum += weight[i]; /* Calculated maximum sum of weights here */
  22.     }
  23.    
  24.     int index = 2 * n;
  25.     binary = new int[index];
  26. /*  An array of twice the number of weights, half the bits indicate presence or absence of weight
  27.     another half bits indicate whether the weight is to be added or subtracted
  28. */
  29.    
  30.     int max = pow(2, index)-1; /* Maximum number of combinations of weights and +- signs */
  31.    
  32.     set <int> s;
  33.     set <int>::iterator it;
  34.    
  35.     for(int i=max; i>0; i--)
  36.     {
  37.         generateBinary(i, index);
  38.        
  39. /*      For all weights from max to 1, generate binary sequence
  40.         First bit for + or - sign; if 1: +, if 0: -
  41.         Next bit will be set fot the weight; 1: included, 0: not included
  42. */     
  43.         int localsum = 0;
  44.         for(int j=1; j<index; j+=2)
  45.         {
  46.             if(binary[j] == 1) /*If the bit is 1, I have to include this weight */
  47.             {
  48.                 if(binary[j-1] == 1) /* If the previous bit is 1, I have to add the weight */
  49.                   localsum += weight[j/2];
  50.                 else
  51.                   localsum -= weight[j/2]; /* If the previous bit is 0, I have to subtract the weight */
  52.             }
  53.         }
  54.         if(localsum > 0)
  55.         {
  56.             s.insert(localsum); /* If sum is positive, insert it into the set */
  57.         }
  58.     }
  59.  
  60.     for(it=s.begin(); it!=s.end(); it++)
  61.       cout << *it << " ";
  62.    
  63.     cout << endl;
  64.    
  65.     delete [] binary;
  66. }
  67.  
  68. void generateBinary(int n, int bits)
  69. {
  70.     for(int i=bits-1; i>=0; i--)
  71.     {
  72.         int k = n >> i;
  73.        
  74.         if(k & 1)
  75.           binary[bits-i-1] = 1;
  76.         else
  77.           binary[bits-i-1] = 0;
  78.     }
  79. }
');