主要思想:先将数组w和数组p按照单价进行排序,利用结构体的index保存其下标。
bound函数是求当前最大可能价值。
backtrack函数是利用回溯法,如果增加当前物品,则想x[i]=1,否则为0。当i>n时,递归调用结束,并且更新数组bestx和bestp。
#include <iostream>
#include <algorithm>
#define N 4
using namespace std;
int c = 7, w[N+1] = {0,3,5,2,1}, p[N+1]={0,9,10,7,4}, cw = 0, cp = 0, bestp = 0, bestx[N+1] = {0}, x[N+1] = {0};
struct node
{
double v;
int index;
}no[N+1];
bool cmp(struct node n1, struct node n2)
{
return n1.v > n2.v;
}
void sort_value()
{
for(int i = 1; i <= N; i++)
{
no[i].v = 1.0*p[i]/w[i];
no[i].index = i;
}
sort(no+1,no+N,cmp);
}
double bound(int i)
{
double cleft = c - cw;
double bound = cp;
while(i <= N && w[no[i].index] <= cleft)
{
cleft -= w[no[i].index];
bound += p[no[i].index];
i++;
}
if(i <= N)
bound += p[no[i].index] / w[no[i].index] * cleft;
return bound;
}
void backtrack(int i)
{
if(i > N)
{
if(cp > bestp)
{
for(int j = 1; j <= N; j++)
bestx[no[j].index] = x[no[j].index];
bestp = cp;
}
return;
}
if(cw + w[no[i].index] <= c)
{
x[no[i].index] = 1, cw += w[no[i].index], cp += p[no[i].index];
backtrack(i+1);
cw -= w[no[i].index], cp -= p[no[i].index];
}
if(bound(i+1) > bestp)
{
x[no[i].index] = 0;
backtrack(i+1);
}
}
int main()
{
sort_value();
backtrack(1);
for(int i = 1; i <= N; i++)
cout << bestx[i] << ' ';
cout << endl;
cout << bestp << endl;
return 0;
}