//
// Subset sum demonstration code.
// Written for ECS 122a by Phil Rogaway (Spring 2000)
//

#include <iostream.h>

const IMPOSSIBLE = -1;
const int N = 5;
const int B = 7;
const int a[] = {0,  3,2,3,6,2};


void PrintSolution(int A[], int i)
{
  if (i==0) return;
  else if (i<0) cout << "ERROR\n";
  else if (A[i]==IMPOSSIBLE) cout << "No Solution Possible\n";
  else {PrintSolution(A, i-a[A[i]]); 
        cout << "Take item " << A[i] << " (which is " << a[A[i]] << ")\n";}
}


void main()
{
  int A[B+1];
  int n, b;
  cout << "Subset Sum Demonstration Code\n\n";

  cout << "The array is [ ";
  for (int i=1; i<=5; i++) cout << a[i] << " "; 
  cout << "] and the target value is " << B << "\n\n";
 
  //
  // OK, here it is!
  //
  for (b=1; b<=B; b++) A[b] = IMPOSSIBLE;
  for (n=1; n<=N; n++) {
    for (b=B; b>=1;b--) {
      if (A[b]==IMPOSSIBLE && 
         (b==a[n] || (a[n]<b && A[b-a[n]]!=IMPOSSIBLE))) A[b]=n;
    }
  }

  PrintSolution(A, B); 
  cout <<"\n";
}

