您的位置:首页 > 其它

杭电ACM_1009贪心法

2013-06-30 19:26 405 查看
       该题目要求出老鼠能够用猫粮换去食物最多的情况,每一个房间的食物除以所要的猫粮数,这个比率越大,则老鼠可在这个房间换取的食物就也多,总共得到的食物也就越多。因此,要先对所有的房间排序,按食物数比上所需猫粮数的比列,按由大到小的顺序排列,放到数组里。这样,老鼠先从数组的第一个元素,即对应的房间换取食物,换取策略是:尽可能多的换取这个房间的食物,如果猫粮能够满足这个房间全部所需的猫粮,则全部换取,否则按老鼠拥有的猫粮与所需猫粮的比例换取食物。

#include <iostream>
#include <algorithm>
using namespace std;

struct node
{
int j;
int f;
double rat;
};

int comp(struct node room1, struct node room2)
{
return room1.rat > room2.rat;
}

int main()
{
int M, N;
int j, f;
double total;
struct node room[1001];

//cout<<"input the M and N"<<endl;
cin>>M>>N;

while(M != -1 && N != -1)
{
total = 0;
for(int i= 0; i < N; i++)
{
cin>>j>>f;

room[i].j = j;
room[i].f = f;
if(f == 0)
room[i].rat = 1000;
else
room[i].rat = 1.0*j/f;  //食物对猫粮的比例
}

sort(room, room+N,comp);   //按rat由大到小的排序

for(int i = 0; i < N; i++)
{
if(M > room[i].f)    //拥有的猫粮满足所需的全部猫粮
{
total += room[i].j;
M = M - room[i].f;
}
else                 //现在拥有的猫粮不足全部所需的猫粮,则按比例换取
{
total += room[i].j * (1.0 * M / room[i].f);
break;
}
}
cout.precision(3);
cout<<fixed<<total<<endl;

cin>>M>>N;

}
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: