#背包问题
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct Bag
{
double v;
double w;
double value;
int num;
} bag[1000];
int sum=0;
bool cmp(Bag a,Bag b)
{
if (a.value>b.value)
return true;
else
return false;
}
void knapsack(int n,double c,double x[],Bag bag[])
{
int i;
sort(bag+1,bag+n+1,cmp);
for(i=1; i<=n; i++)
{
if(bag[i].w>c)
{
x[bag[i].num]=c/bag[i].w;
sum=sum+c/bag[i].w*bag[i].v;
break;
}
else
{
c=c-bag[i].w;
sum=sum+bag[i].v;
x[bag[i].num]=1;
}
}
}
int main()
{
int n;
double c;
double x[1000];
memset(x,0,sizeof(x));
cout<<"输入物品的个数和背包的容量"<<endl;
cin>>n>>c;
cout<<"输入物品的质量和价值"<<endl;
for(int i=1; i<=n; i++)
{
cin>>bag[i].w>>bag[i].v;
bag[i].num=i;
bag[i].value=bag[i].v/bag[i].w;
}
knapsack(n,c,x,bag);
cout<<"输出总价值为"<<sum<<endl;
for(int i=1; i<=n; i++)
cout<<x[i]<<" ";
cout<<endl;
return 0;
}
贪心--背包问题
最新推荐文章于 2024-08-11 22:03:13 发布