• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
\0\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;
}

  

此博客主要是个人记录
posted on 2015-03-25 20:47  \0\0\0  阅读(153)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3