题解 贪心专题(2.1-2.7) 之 E-H

202 阅读1分钟

题目E:Fat Mouse's Trade

FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean.
The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[i]* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain.

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.

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.

数据范围:all integers<=1000.

输入样例:

5 3
7 2
4 3
5 2
20 3
25 18
24 15
15 10
-1 -1

输出样例:

13.333
31.500

题解思路:

此题类似01背包问题,但可以不装完,所以可以用贪心算法解决。

对每一次交易的比率从大到小排序,选取最大比率的交易依次进行。

例如样例1,计算出每个交易的比率J[i]/F[i],分别为3.5,1.33,2.5,所以先用2个猫粮买7个咖啡豆,再用2个猫粮买5个咖啡豆,之后只剩1咖啡豆,可以买4/3个咖啡豆,总共获得13.333个。

题解:

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

struct warehouse{
	int j,f;
	double rate;
}p[1007];

bool compare(warehouse a,warehouse b){
	return a.rate>b.rate;
}

int main(){
	int m,n;
	double r=0;
	while(true){
		scanf("%d%d",&m,&n);
		if(m==-1){
			return 0;
		}
		for(int i=0;i<n;i++){  //calculate each rate of the warehouse
			scanf("%d%d",&p[i].j,&p[i].f);
			p[i].rate=(double)(p[i].j)/(double)(p[i].f);
		}
		sort(p,p+n,compare);
		r=0;
		for(int i=0;i<n;i++){
			if(m>0){
				if(m>=p[i].f){
					r+=(double)p[i].j;
					m-=p[i].f;
				}
				else{
					r+=(double)p[i].j*(double)m/(double)p[i].f;
					break;
				}
			}
			else{
				break;
			}
		}
		printf("%.3lf\n",r);
	}
} 

题目F:

数据范围:

输入样例:

输出样例:

题解思路:

题解:

题目G:

数据范围:

输入样例:

输出样例:

题解思路:

题解:

题目H:

数据范围:

输入样例:

输出样例:

题解思路:

题解:

题目I:

数据范围:

输入样例:

输出样例:

题解思路:

题解:

题目J:

数据范围:

输入样例:

输出样例:

题解思路:

题解:

题目K:

数据范围:

输入样例:

输出样例:

题解思路:

题解: