复习题解集——老鼠与猫的交易

题目:

有一只老鼠很喜欢奶酪,但是奶酪被分别放在N个房间里,而且这些房间都有一只猫咪看守,现在它准备和猫咪们做个交易。它有M磅的猫食,想用这M磅猫食换取奶酪。在猫咪看守的每一个房间里有奶酪J[i]磅,同时猫咪需要F[i]磅的食物,如果老鼠给猫咪Fi%的猫食,那么它就可以得到Ji%的奶酪。现在已知每只猫咪对猫食的需求量和每个房间的奶酪数,那老鼠怎样才能换得最多的奶酪呢?

题解:

入门水题,用性价比排序即可(a[i] / b[i]),基本读懂题就没问题了吧。。。。

代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int n, m;
struct jj{
	double x, y, xin;
}a[100005];
int cmp(jj xx, jj yy) {
	return xx.xin > yy.xin;
}
int main() {
	scanf("%d %d", &m, &n);
	for(int i = 1;i <= n; i++) {
		scanf("%lf %lf", &a[i].x, &a[i].y);
		a[i].xin = a[i].x / a[i].y;
	}
	sort(a + 1, a + 1 + n, cmp);
	double sum = 0, sum2;
	for(int i = 1;i <= n; i++) {
		if(sum + a[i].y <= m) {
			sum2 += a[i].x;
			sum+=a[i].y;
		}
		else{
			sum2 += (a[i].x / a[i].y) * (m - sum);
			break;
		}
	}
	printf("%.3lf", sum2);
	return 0; 
}

猜你喜欢

转载自blog.csdn.net/cqbz_lipengcheng/article/details/107288968