例题1.1 勇者斗恶龙 UVa11292

1.题目描述:点击打开链接

2.解题思路:本题用贪心法解决,事先对恶龙的直径,能力值从小到大排序,由于要试图杀掉所有的恶龙,因此枚举每只恶龙,用cur来表示当前骑士的下标,如果他恰好能杀掉恶龙,就用他,否则尝试下一个。如果cur与m相等时退出循环,若此时恶龙仍未被杀光,则无解,反之输出ans。

3.代码:

#define _CRT_SECURE_NO_WARNINGS 
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<set>
#include<vector>
#include<stack>
#include<map>
#include<queue>
#include<deque>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<functional>
using namespace std;

const int N = 20000 + 10;
int a[N], b[N];
int main()
{
	freopen("t.txt", "r", stdin);
	int n, m;
	while (cin >> n >> m && (n || m))
	{
		memset(a, 0, sizeof(a));
		memset(b, 0, sizeof(b));
		for (int i = 0; i < n; i++)cin >> a[i];
		for (int i = 0; i < m; i++)cin >> b[i];
		sort(a, a + n);
		sort(b, b + m);
		int ans = 0, i;
		int cur = -1,flag = 1;
		for (i = 0; i < n; i++)//枚举恶龙
		{
			while (++cur < m)
				if (b[cur] >= a[i]) { ans += b[cur]; break; }
			if (cur == m)break;
		}
		if (i < n)flag = 0;
		if (!flag)printf("Loowater is doomed!\n");
		else printf("%d\n", ans);
	}
	return 0;
}

你可能感兴趣的:(贪心法)