Accept: 108 Submit: 689
Time Limit: 3000 mSec
Problem Description
The capital of Ardenia is surrounded by several lakes, and each of them is initially full of water. Currently, heavy rainfalls are expected over the land. Such a rain falls to one of the lakes: if the lake is dry and empty, then it will be filled with water; if the lake is already full, then it will overflow, which will result in a natural disaster. Fortunately, the citizens have a dragon at their disposal (and they will not hesitate to use it). The dragon may drink the whole water from a lake in one sitting. Also, the mages of Ardenia already predicted the weather conditions for the next couple of years. The only question is: from which lake and when should the dragon drink to prevent a catastrophe?
Input
The input contains several test cases. The first line of the input contains a positive integer Z ≤ 40, denoting the number of test cases. Then Z test cases follow, each conforming to the format described below. The first line of the input instance contains two space-separated positive integers n ≤ 106 andm ≤ 106 , where n is the number of lakes. (There are at most 10 input instances for which n ≥ 105or m ≥ 105.) The second line contains the weather forecast for the next m days: m space-separated integers t1,t2,...,tm (ti ∈ [0,n]). If ti ∈ [1,n], it means a heavy rainfall over lake ti at day i. If ti = 0, there is no rain at day i, and the dragon has the time to drink the water from one lake of your choice. Note that the dragon does not drink on a rainy day.
Output
Sample Input
2 4
0 0 1 1
2 4
0 1 0 2
2 3
0 1 2
2 4
0 0 0 1
Sample Output
NO
YES
1 2
NO
YES
0 1 0
题解:这个题应该算是并查集的应用吧,贪心虽然有,但是很明显,没什么可说的。并查集维护某个位置往后第一个晴天,从前往后扫,遇到一个下雨天,就看所下到的那个湖x前一次被灌满时什么时候,查询对应位置之后的第一个晴天,喝了湖x的水即可。
#include <bits/stdc++.h> using namespace std; const int maxn = + ; int read() {
int q = ; char ch = ' ';
while (ch<'' || ch>'') ch = getchar();
while ('' <= ch && ch <= '') {
q = q * + ch - '';
ch = getchar();
}
return q;
} int n, m;
int rain[maxn], pre[maxn], fa[maxn];
int ans[maxn]; int findn(int x) {
return x == fa[x] ? x : fa[x] = findn(fa[x]);
} bool solve() {
memset(pre, , sizeof(pre));
memset(ans, , sizeof(ans));
for (int i = ; i <= m; i++) {
if (!rain[i]) continue;
int x = findn(pre[rain[i]]);
if (x < i) {
fa[x] = findn(x + );
ans[x] = rain[i];
}
else return false;
pre[rain[i]] = i;
}
printf("YES\n");
for (int i = ; i <= m; i++) {
if (!rain[i]) {
printf("%d ", ans[i]);
}
}
printf("\n");
return true;
} int main()
{
//freopen("input.txt", "r", stdin);
int iCase;
iCase = read();
while (iCase--) {
//n = read(), m = read();
scanf("%d%d", &n, &m);
for (int i = ; i <= m; i++) {
//rain[i] = read();
scanf("%d", &rain[i]);
} int last = m + ;
fa[m + ] = m + ;
for (int i = m; i >= ; i--) {
if (!rain[i] && i) last = i;
fa[i] = last;
} if (!solve()) {
printf("NO\n");
}
}
return ;
}