- #include<iostream>
- using namespace std;
- #define N 4
- unsigned int S=0;
- unsigned int Weight[N];
- int main()
- {
- cout<<"Plz input the "<<N<<" goods's weight/n";
- for(int i=0;i<N;i++)cin>>Weight[i];
- cout<<"Input the package volume/n";
- cin>>S;
- int flag[N]={0};
- int i, j, z, csum, MAXZ=1;
- for(i=0;i<N;i++)MAXZ=MAXZ<<1;
- for(i=0;i<MAXZ; i++)
- {
- j=i;
- for(z=0;z<N;z++){flag[z]=j%2; j=j>>1;}
- for(z=0,csum=0; z<N; z++) if(flag[z]){csum+=Weight[z]; if(csum>S)break;}
- if(csum==S)
- {
- for(z=0;z<N;z++)if(flag[z])cout<<Weight[z]<<" ";
- cout<<endl;
- break;
- }
- }
- getchar();
- cin>>S;
- return 0;
- }
/*
背包问题简化:
有个背包可以装入S重量的东西,现在有N个物品,分别重w1,w2,w3...wn
找到一组解令其之和为S,用非递归实现
*/