老鼠的旅行
題目源地址
Description
一只老鼠有M磅貓食,然后在N個房間里面用貓食換JavaBean,房間i中能用F[i]磅的貓食來換J[i]磅的JavaBean,而且老鼠可以在一個房間里根據一定比例a%來換取JavaBean. 現在他是這任務分配給你:告訴他,他的JavaBeans的獲取能最多。Input
The input consists of multiple test cases. Each test case begins with a line containing two non-negative integers M and N. Then N lines follow, each contains two non-negative integers J[i] and F[i] respectively. The last test case is followed by two -1′s. All integers are not greater than 1000. M是開始時老鼠有的貓食!Output
For each test case, print in a single line a real number accurate up to 3 decimal places, which is the maximum amount of JavaBeans that FatMouse can obtain.Sample Input
5 3 7 2 4 3 5 2 20 3 25 18 24 15 15 10 -1 -1Sample Output
13.333 31.500 1 #include <iostream> 2 #include <stdio.h> 3 #include <algorithm> 4 using namespace std; 5 struct sa{ 6 int j; 7 int f; 8 double awk; 9 }data[1001]; 10 int cmp(const sa &a,const sa &b) 11 { 12 return (a.awk)>(b.awk);//為什么要用const 13 } 14 15 int main() 16 { 17 int m,n; 18 double sum; 19 int i; 20 while (cin>>m>>n) 21 { 22 sum=0; 23 if (m==-1&&n==-1) 24 break; 25 for (i=0;i<n;i++) 26 { 27 cin>>data[i].j>>data[i].f; 28 data[i].awk=(double)data[i].j/data[i].f; 29 } 30 sort (data,data+n,cmp); 31 for (i=0;i<n;i++) 32 { 33 if (m>=data[i].f) 34 { 35 sum=sum+data[i].j; 36 m=m-data[i].f; 37 38 } 39 else 40 { 41 sum=sum+m*data[i].awk;//m很小的時候一個個算 42 break;//沒走完所有的房間就沒有貓糧了 43 } 44 45 }printf ("%.3f\n",sum); 46 } 47 48 return 0; 49 }貪心算法: 貪心法并不是從整體最優考慮,它所做出的選擇只是在某種意義上的局部最優。 這種局部最優選擇并不總能獲得整體最優解(Optimal Solution),但通常能獲得近似最優解(Near-Optimal Solution)。 例:用貪心法求解付款問題。 假設有面值為5元、2元、1元、5角、2角、1角的貨幣,需要找給顧客4元6角現金,為使付出的貨幣的數量最少,首先選出1張面值不超過4元6角的最大面值的貨幣,即2元,再選出1張面值不超過2元6角的最大面值的貨幣,即2元,再選出1張面值不超過6角的最大面值的貨幣,即5角,再選出1張面值不超過1角的最大面值的貨幣,即1角,總共付出4張貨幣。
轉載于:https://www.cnblogs.com/twomeng/p/9476051.html
總結
- 上一篇: arduino蓝牙通讯代码_arduin
- 下一篇: 安卓蓝牙通讯