Accept: 108 Submit: 689Time 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
Sample Output
NO
YES1 2NOYES0 1 0
题解:这个题应该算是并查集的应用吧,贪心虽然有,但是很明显,没什么可说的。并查集维护某个位置往后第一个晴天,从前往后扫,遇到一个下雨天,就看所下到的那个湖x前一次被灌满时什么时候,查询对应位置之后的第一个晴天,喝了湖x的水即可。
1 #include2 3 using namespace std; 4 5 const int maxn = 1000000 + 100; 6 7 int read() { 8 int q = 0; char ch = ' '; 9 while (ch<'0' || ch>'9') ch = getchar();10 while ('0' <= ch && ch <= '9') {11 q = q * 10 + ch - '0';12 ch = getchar();13 }14 return q;15 }16 17 int n, m;18 int rain[maxn], pre[maxn], fa[maxn];19 int ans[maxn];20 21 int findn(int x) {22 return x == fa[x] ? x : fa[x] = findn(fa[x]);23 }24 25 bool solve() {26 memset(pre, 0, sizeof(pre));27 memset(ans, 0, sizeof(ans));28 for (int i = 1; i <= m; i++) {29 if (!rain[i]) continue;30 int x = findn(pre[rain[i]]);31 if (x < i) {32 fa[x] = findn(x + 1);33 ans[x] = rain[i];34 }35 else return false;36 pre[rain[i]] = i;37 }38 printf("YES\n");39 for (int i = 1; i <= m; i++) {40 if (!rain[i]) {41 printf("%d ", ans[i]);42 }43 }44 printf("\n");45 return true;46 }47 48 int main()49 {50 //freopen("input.txt", "r", stdin);51 int iCase;52 iCase = read();53 while (iCase--) {54 //n = read(), m = read();55 scanf("%d%d", &n, &m);56 for (int i = 1; i <= m; i++) {57 //rain[i] = read();58 scanf("%d", &rain[i]);59 }60 61 int last = m + 1;62 fa[m + 1] = m + 1;63 for (int i = m; i >= 0; i--) {64 if (!rain[i] && i) last = i;65 fa[i] = last;66 }67 68 if (!solve()) {69 printf("NO\n");70 }71 }72 return 0;73 }