#include<stdio.h>
#define n 3
int maxvalue=0,tot=0;
int w[n]={16,15,15},v[n]={45,25,25},c=30;
int tempweight=0,tempvalue=0;
void dfs(int t)
{
if(t==n)
{
if(tempvalue>maxvalue && tempweight<=c)
maxvalue=tempvalue;
return;
}
//left subtree
if(tempvalue<=c && tempvalue+tot>maxvalue)
{
tempvalue+=v[t];
tempweight+=w[t];
tot-=v[t];
dfs(t+1);
tempvalue-=v[t];
tempweight-=w[t];
tot+=v[t];
}
//right subtree
if(tempvalue+tot>maxvalue)
{
tot+=v[t];
dfs(t+1);
tot-=v[t];
}
}
int main()
{
int i;
for(i=0;i<n;i++)
{
tot+=v[i];
}
dfs(0);
printf("%d\n",maxvalue);
return 0;
}
#define n 3
int maxvalue=0,tot=0;
int w[n]={16,15,15},v[n]={45,25,25},c=30;
int tempweight=0,tempvalue=0;
void dfs(int t)
{
if(t==n)
{
if(tempvalue>maxvalue && tempweight<=c)
maxvalue=tempvalue;
return;
}
//left subtree
if(tempvalue<=c && tempvalue+tot>maxvalue)
{
tempvalue+=v[t];
tempweight+=w[t];
tot-=v[t];
dfs(t+1);
tempvalue-=v[t];
tempweight-=w[t];
tot+=v[t];
}
//right subtree
if(tempvalue+tot>maxvalue)
{
tot+=v[t];
dfs(t+1);
tot-=v[t];
}
}
int main()
{
int i;
for(i=0;i<n;i++)
{
tot+=v[i];
}
dfs(0);
printf("%d\n",maxvalue);
return 0;
}
本文介绍了一个使用深度优先搜索解决背包问题的C语言程序实例。该程序通过递归地选择物品装入背包,使得背包的价值最大化,同时不超过背包的重量限制。代码中详细展示了如何进行状态转移以及剪枝操作。
815

被折叠的 条评论
为什么被折叠?



