题目为:
运用贪心算法思想,及局部最优,则整体最优
- c++代码如下:
//饮品混合
#include<bits/stdc++.h>
using namespace std;
const int M=510;
struct good{
double price;
double weight;
double ratio; //性价比
};
good s[M];
bool comp(const good x,const good y)
{
return x.ratio>y.ratio;
}
main()
{
int i=0, ans = 0, c, n;
cout<<"输入容器的体积和商品的数量 :";
cin>>c>>n; //容器的体积
cout<<"分别输入每个商品价格和对应的体积:\n";
for(int j=0;j<n;j++)
{
cin>>s[j].price>>s[j].weight; s[j].ratio=s[j].price/ s[j].weight;
}
sort(s,s+n,comp); //安性价比从大到小排序
while(c>0 && i<= n)
{
if(s[i].weight<=c)
{
ans = ans+s[i].price; c = c-s[i].weight;
}else{
ans = ans+s[i].price*c/s[i].weight;
c = 0;
}
i = i+1;
}
cout<<"混合饮品的最高价格:"<<ans;
return 0;
}
运行结果
输入容器的体积和商品的数量 :800 5
分别输入每个商品价格和对应的体积:
60 600
10 250
36 200
16 100
45 300
的最高价格:117
--------------------------------
注意: 我在使用c++的sort()函数时,对结构体数组排序时,数组下标必须是从0开始,否则会出错,找了半天,终于发现问题所在!