您的位置:首页 > 编程语言 > Go语言

UVa 1623:Enter the Dragon(贪心)

2015-08-27 23:11 483 查看
题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=845&page=show_problem&problem=4498

题意:某城市里有n个湖,每个湖都装满了水。天气预报显示不久的将来会有暴雨。具体来说,在接下来的m天内,每天要么不下雨,要么恰好往一个湖里下暴雨。如果这个湖已经装满了水,将会引发水灾。为了避免水灾,市长请来一只神龙,可以在每个不下雨的天里喝干一个湖里的水(也可以不喝)。如果以后再往这个干枯的湖里下暴雨,湖会重新被填满,但不会引发水灾。神龙应当如何喝水才能避免水灾。(本段摘自《算法竞赛入门经典(第2版)》)

分析:

贪心策略,对于当前下雨的湖而言,去找上一次湖被填满的时刻,用最靠近那个时刻的不下雨的日子去把湖水喝干。可以使用set来查找时刻。

代码:

#include <iostream>
#include <algorithm>
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <set>

using namespace std;

const int maxn = 1000000 + 5;

int T, n, m, x;
bool flag, first;
int ans[maxn], last[maxn];
set< int > s;
set< int >::iterator it;

int main()
{
scanf("%d", &T);
for (int C = 0; C < T; ++C)
{
flag = true;
s.clear();
memset(ans, 0, sizeof(ans));
memset(last, 0, sizeof(last));
scanf("%d%d", &n, &m);
for (int i = 0; i < m; ++i)
{
scanf("%d", &x);
if (flag)
{
if (x)
{
ans[i] = -1;
it = s.lower_bound(last[x]);
if (it == s.end())
flag = false;
else
{
ans[*it] = x;
last[x] = i;
s.erase(*it);
}
}
else
s.insert(i);
}
}
if (flag)
{
first = true;
printf("YES\n");
for (int i = 0; i < m; ++i)
if (ans[i] >= 0)
{
if (first)
{
printf("%d", ans[i]);
first = false;
}
else
printf(" %d", ans[i]);
}
printf("\n");
}
else
printf("NO\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: