演算法實驗5《演算法綜合實驗》
阿新 • • 發佈:2019-02-08
使用回溯法解決0-1揹包問題
#include<iostream>
using namespace std;
int n, c, bestp; //物品的個數,揹包的容量,最大價值
int p[80], w[80], x[80], bestx[80]; //物品的價值,物品的重量,x[i]暫存物品的選中情況,物品的選中情況
void Backtrack(int i, int cp, int cw)
{ //cw當前包內物品重量,cp當前包內物品價值
int j;
if (i>n)//回溯結束
{
if (cp>bestp)
{
bestp = cp;
for (i = 0; i <= n; i++) bestx[i] = x[i];
}
}
else
for (j = 0; j <= 1; j++)
{
x[i] = j;
if (cw + x[i] * w[i] <= c)
{
cw += w[i] * x[i];
cp += p[i] * x[i];
Backtrack(i + 1, cp, cw);
cw -= w[i] * x[i];
cp -= p[i] * x[i];
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
bestp = 0;
cout << "輸入揹包最大容量,物品個數,物品的重量,物品的價值\n";
cin >> c;
cin >> n;
for (int i = 1; i <= n; i++)cin >> w[i];
for (int i = 1; i <= n; i++)cin >> p[i];
Backtrack(1, 0, 0);
cout << "最大價值為:" << bestp;
printf("\n被選中的物品依次是\n");
for (int i = 1; i <= n; i++) if (bestx[i])cout << "第" << i << "個物品" << endl;
system("pause>nul");
return 0;
}