設計如圖
需要該pdf文檔,直接下載即可
代碼如下
//author:rgh
#include <stdio.h>
#include <queue>
using namespace std;
#define MAXN 20 //最多可能物品數
#define INF 0x3f3f3f3f3 //定義∞
//問題表示
int n=3,W=30;
int w[]={0,16,15,15};//重量,下標0不用
int v[]={0,45,25,25};//價值,下標0不用
//求解結果表示
int maxv=-9999;//存放最大價值,全局變量
int bestx[MAXN];//存放最優解,全局變量
int total=1;//解空間中結點數累計,全局變量
struct NodeType //隊列中的結點類型
{ int no;//結點編號
int i;//當前結點在搜索空間中的層次
int w;//當前結點的總重量
int v;//當前結點的總價值
int x[MAXN];//當前結點包含的解向量
double ub;//上界
bool operator<(const NodeType &s) const //重載<關係函數
{
return ub<s.ub;//ub越大越優先出隊
}
};
void bound(NodeType &e)//計算分枝結點e的上界
{
int i=e.i+1;//第一層i=1;
int sumw=e.w;//m=0;
double sumv=e.v;//V=0;
while ((sumw+w[i]<=W) && i<=n)
{ sumw+=w[i];//計算揹包已裝入載重
sumv+=v[i];//計算揹包已裝入價值
i++;
}//只能裝入w[1]此時sumw=16sumv=45i=2
if (i<=n)
e.ub=sumv+(W-sumw)*v[i]/w[i];//e.ub=45+14*25/15=68;//
else
e.ub=sumv;
}
int EnQueue(NodeType e,priorit._queue<NodeType> &qu)//結點e進隊qu
{ //e1.queue
if (e.i==n)//到達葉子結點//否
{
if (e.v>maxv)//找到更大價值的解
{
maxv=e.v;
for (int j=1;j<=n;j++)
bestx[j]=e.x[j];
}
}
else qu.push(e1);//非葉子結點進隊
}
void bfs() //求0/1揹包的最優解
{
int j;
NodeType e,e1,e2; //定義3個結點
priority_queue<NodeType> qu;//定義一個隊列大根堆
e.i=0; //根結點置初值,其層次計爲0
e.w=0; e.v=0;
e.no=total++;//e.no=1;total =2;
for (j=1;j<=n;j++)
e.x[j]=0;
bound(e); //求根結點的上界
qu.push(e); //根結點進隊0[no=1w=0v=0,x[000]ub=68
while (!qu.empty()) //隊不空循環
{
e=qu.top(); qu.pop();//出隊結點e//0[no=1w=0v=0,x[000]ub=68
if (e.w+w[e.i+1]<=W)//剪枝:檢查左孩子結點
{
e1.no=total++; no=2 total=3
e1.i=e.i+1; //建立左孩子結點=1
e1.w=e.w+w[e1.i];=16
e1.v=e.v+v[e1.i];=45
for (j=1;j<=n;j++)//複製解向量
e1.x[j]=e.x[j];
e1.x[e1.i]=1;//X[100]
bound(e1); //求左孩子結點的上界//ub=68
EnQueue(e1,qu);//1[no=2w=16v=45,x[100]ub=68 //左孩子結點進隊操作
}
e2.no=total++;//建立右孩子結點//no=3 total=4
e2.i=e.i+1;//=1;
e2.w=e.w; e2.v=e.v;//0,0
for (j=1;j<=n;j++)//複製解向量
e2.x[j]=e.x[j];
e2.x[e2.i]=0;//X[000]
bound(e2);//求右孩子結點的上界50
if (e2.ub>maxv)//若右孩子結點可行,則進隊,否則被剪枝
EnQueue(e2,qu);//1[no=3w=v=0,x[000]ub=50
}
}
int main()
{
bfs();//調用隊列式分枝限界法求0/1揹包問題
printf("分枝限界法求解0/1揹包問題:\n X=[");
for(int i=1;i<=n;i++)//輸出最優解
printf("%2d",bestx[i]); //輸出所求X[n]數組
printf("],裝入總價值爲%d\n",maxv);
return 0;
}
是不是你要的呀,覺得好點個贊吧