【CVTE】买虾问题
题目:
标签:贪心算法
算法代码:
思路;
1.先对虾的单价进行排序,从低到高
2.进行计算
完整代码
#include<iostream>
#include<vector>
using namespace std;
struct Shrimp{
int price; //单价
int total; //库存
};
// 排序1:快速排序
void quick_sort(vector<Shrimp> &menu, int left, int right)
{
if(left>=right) return;
Shrimp pivot=menu[left];
int i=left,j=right;
while(i<j)
{
while(i<j && menu[j].price>pivot.price) j--;
while(i<j && menu[i].price<=pivot.price) i++;
if(i!=j)
{
Shrimp temp=menu[i];
menu[i]=menu[j];
menu[j]=temp;
}
}
if(i!=left)
{
menu[left]=menu[i];
menu[i]=pivot;
}
quick_sort(menu, left, i-1);
quick_sort(menu, i+1, right);
}
void quick_sort(vector<Shrimp> &menu )
{
quick_sort(menu, 0, menu.size()-1);
}
float computeBuyWeight(int money, const vector<Shrimp>& shrimp)
{
if(money<=0) return 0.0;
//复制菜单
vector<Shrimp> menu(shrimp.size());
for(int i=0; i<shrimp.size();i++)
menu[i]=shrimp[i];
//对menu进行快速排序
quick_sort(menu);
//贪心算法
float leftmoney=money;
float result=0.0;
for(int i=0; i<menu.size(); i++)
{
if(leftmoney>(menu[i].price*menu[i].total))
{
leftmoney-=menu[i].price*menu[i].total;
result+=menu[i].total;
}
else
{
result+=(leftmoney/menu[i].price);
return result;
}
}
return result;
}
int main()
{
Shrimp s1;
s1.price=4;
s1.total=4;
Shrimp s2;
s2.price=3;
s2.total=3;
vector<Shrimp> sh;
sh.push_back(s1);
sh.push_back(s2);
cout<<computeBuyWeight(100, sh);
}