POJ3614 Sunscreen 贪心

题目链接

http://poj.org/problem?id=3614

分析

贪心,将奶牛按 minSPF 降序排序,依次考虑每头奶牛,在能用的防晒霜中选择 SPF 最大的使用。

假设选择 SPF 较小的使用,则可能会出现后来 SPF 最大的防晒霜无法再使用,造成浪费。

一瓶防晒霜最多使一头奶牛满足要求,当前奶牛放弃不用答案也不会更优。

AC代码

#include 
#include 

using namespace std;

inline int read() {
	int num = 0;
	char c = getchar();
	while (c < '0' || c > '9') c = getchar();
	while (c >= '0' && c <= '9')
		num = num * 10 + c - '0', c = getchar();
	return num;
}

const int maxn = 2505;

struct Cow {
	int mins, maxs;

	bool operator < (const Cow& rhs) const {
		return mins > rhs.mins;
	}
} cow[maxn];

struct Cream {
	int s, c;

	bool operator < (const Cream& rhs) const {
		return s > rhs.s;
	}
} cream[maxn];

int main() {
	int c = read(), l = read(), cnt = 0;
	for (int i = 1; i <= c; ++i)
		cow[i].mins = read(), cow[i].maxs = read();
	for (int i = 1; i <= l; ++i)
		cream[i].s = read(), cream[i].c = read();
	sort(cow + 1, cow + c + 1);
	sort(cream + 1, cream + l + 1);
	for (int i = 1; i <= c; ++i)
		for (int j = 1; j <= l; ++j) {
			if (!cream[j].c) continue;
			if (cream[j].s >= cow[i].mins && cream[j].s <= cow[i].maxs) {
				--cream[j].c, ++cnt;
				break;
			}
		}
	printf("%d", cnt);
	return 0;
}

你可能感兴趣的:(《算法竞赛进阶指南》)