数据结构书上的背包问题,最基本的背包问题。
简单回溯,数字模拟栈。
#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int totalweight;
cin>>totalweight;
int num;
cin>>num;
int weis[100];
for(int i = 0; i < num; i++)
{
cin>>weis[i];
}
//
int stack[100];
int top = -1;
int leftwei = totalweight;
int trying = 0;
while(top != -1 || trying != num)
{
while( leftwei - weis[trying] >= 0 && trying < num)
{
top++;
stack[top] = trying;
leftwei -= weis[trying];
trying++;
}
if(leftwei == 0)
{
for(int i = 0; i < top + 1; i++)
{
cout<<stack[i]<<" ";
}
cout<<endl;
leftwei = weis[stack[top]];
trying = stack[top] + 1;
top--;
}
else if( trying >= num)
{
leftwei += weis[stack[top]];
trying = stack[top] + 1;
top--;
}
else
trying++;
}
return 0;
}