问题是如何使用以下信息跟踪贪婪算法的背包问题?
P=[10,7,12,13,6,20]
W=[3,2,4,3,13,8]
M=15
n=6
如果有人可以帮助我理解这一点或者指出我正确的方向,我会很感激。
答案 0 :(得分:2)
好吧,如果它是'分数背包'(即你可以拿走一小部分物品)那么这很简单:
项目(作为价格,重量对)[(10,3),(7,2),(12,4),(13,3),(6,13),(20,8)]
直观地说,你首先要获得一件物品,这样可以提供更多的价格和更轻的重量。所以,让我们按照价格与重量比对商品进行排序:
[(13,3),(7,2),(10,3),(12,4),(20,8),(6,13)]
现在,在你的产能或物品用完之前,尽可能多地拿走最有价值的物品。
0. cap = 15, price = 0
1. Take (13, 3): cap = 12, price = 13
2. Take (7, 2): cap = 10, price = 20
3. Take (10, 3): cap = 7, price = 30
4. Take (12, 4): cap = 3, price = 42
5. Take (20, 8): cap = 0, price = 49.5
[in this step, you have capacity to take 3 units, so take 3 units of the 5th item, the price of which is 3*20/8]
如果你不能采取分数项目,那么这种贪婪的方法可能无法为你提供最佳解决方案。
答案 1 :(得分:0)
在第一步中,即1.取(13,3):上限= 12,价格= 15, 因为添加了3个项目,所以价格将是13 * 3 = 39 ...它以相同的方式进行。当再添加2个时,则添加7 * 2 = 14。因此,步骤2中的成本将是39 + 14 = 53。
答案 2 :(得分:0)
#include<iostream>
#include<time.h>
using namespace std;
int r;
int* sort(int list[],int n)
{
int temp;
bool swap =true;
int i;
while(swap)
{
for(i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(list[i]>list[j])
{
temp=list[j];
list[j]=list[i];
list[i]=temp;
swap= true;
}else
{
swap= false;
}
}
}
}
return (list);
}
int* knapsack(int list[],int k)
{
const int n=6;
int c=0;
int ks[n];
int sum=0;
int u;
for(int i=0;i<n;i++)
{
sum=sum+list[i];
if(sum<=k)
{
u=list[i];
ks[i]=u;
list[i]=i+1;
c++;
//cout<<"Index number in sorted list : "<<i+1<<" "<<endl;
}
}
r=c;
return (list);
}
int main()
{
double difference1,difference2;
clock_t start,end;
const int m=5;
int list[m]={8,6,7,4,9};
cout<<"Your list of sizes of parcel : ";
for(int i=0;i<m;i++)
{
cout<<list[i]<<" ";
}
cout<<endl<<endl;
start = clock();
int* x=sort(list,m); //call to sorting function to sort the list in increasing size order.
end = clock();
difference1=((start-end)/CLOCKS_PER_SEC);
cout<<"Sorted list of sizes of parcel : ";
for (int j = 0; j <m; j++)
{cout<<x[j]<<" ";}
cout<<endl<<endl;
111
int k=24; //Size of sack
start = clock();
int* g= knapsack(list,k); //call to knapsack function
end = clock();
difference2=((start-end)/CLOCKS_PER_SEC);
cout<<"Indexes taken from sorted list : ";
for(int l=0;l<r;l++)
{
cout<<g[l]<<" ";
}
cout<<endl<<endl;
cout<<"Time elapsed : "<<(difference1+difference2)<<endl<<endl;
}