首页 > 其他 > 详细

背包一

时间:2015-03-25 22:56:49      阅读:150      评论:0      收藏:0      [点我收藏+]

数据结构书上的背包问题,最基本的背包问题。

简单回溯,数字模拟栈。

#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;
}

  

背包一

原文:http://www.cnblogs.com/coralyms/p/4366876.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!