標籤:shu 允許 cte 興趣 ext inpu win closed class
題目描述
Farmer John and his cows are planning to leave town for a long vacation, and so FJ wants to temporarily close down his farm to save money in the meantime.
The farm consists of NN barns connected with MM bidirectional paths between some pairs of barns (1 \leq N, M \leq 30001≤N,M≤3000). To shut the farm down, FJ plans to close one barn at a time. When a barn closes, all paths adjacent to that barn also close, and can no longer be used.
FJ is interested in knowing at each point in time (initially, and after each closing) whether his farm is "fully connected" -- meaning that it is possible to travel from any open barn to any other open barn along an appropriate series of paths. Since FJ‘s farm is initially in somewhat in a state of disrepair, it may not even start out fully connected.
FJ和他的奶牛們正在計劃離開小鎮做一次長的旅行,同時FJ想臨時地關掉他的農場以節省一些金錢。
這個農場一共有被用M條雙向道路串連的N個穀倉(1<=N,M<=3000)。為了關閉整個農場,FJ 計劃每一次關閉掉一個穀倉。當一個穀倉被關閉了,所有的串連到這個穀倉的道路都會被關閉,而且再也不能夠被使用。
FJ現在正感興趣於知道在每一個時間(這裡的“時間”指在每一次關閉穀倉之前的時間)時他的農場是否是“全連通的”——也就是說從任意的一個開著的穀倉開始,能夠到達另外的一個穀倉。注意自從某一個時間之後,可能整個農場都開始不會是“全連通的”。
輸入輸出格式
輸入格式:
The first line of input contains NN and MM. The next MM lines each describe a
path in terms of the pair of barns it connects (barns are conveniently numbered
1 \ldots N1…N). The final NN lines give a permutation of 1 \ldots N1…N
describing the order in which the barns will be closed.
輸出格式:
The output consists of NN lines, each containing "YES" or "NO". The first line
indicates whether the initial farm is fully connected, and line i+1i+1 indicates
whether the farm is fully connected after the iith closing.
輸入輸出範例輸入範例#1:
4 31 22 33 43412
輸出範例#1:
YESNOYESYES
這道題有一個判連通性過程,馬上應該想到並查集這種好東西,但是我們從一個集合去拆肯定會很麻煩的,時間上也無法被允許,那麼我們正難則反,既然正著推比較麻煩,那我們為什麼不把這個關閉的過程倒過來想象成開啟呢,剛開始都是關閉狀態,然後一個個開啟,最後倒著輸出即可,不多說了上代碼
#include <cstdio>#include <algorithm>#include <cstring>using namespace std;int n,m,a[3005][3005],p[3005],check[3005],fa[3005],ans[3005];int find(int x){ if(fa[x]==x) return x; return fa[x]=find(fa[x]);}int main(){ scanf("%d%d",&n,&m); for(int i=1;i<=m;i++){ int x,y; scanf("%d%d",&x,&y); a[x][y]=a[y][x]=1; } for(int i=1;i<=n;i++){ fa[i]=i; scanf("%d",&p[i]); } for(int i=n;i>=1;i--){ check[p[i]]=1; for(int j=1;j<=n;j++) if(check[j]&&a[p[i]][j]){ //if(i==2) printf("%d %d\n",p[i],j); fa[find(p[i])]=find(j); } int cnt=0; for(int j=1;j<=n;j++) if(check[j]&&fa[j]==j) cnt++; if(cnt>1) ans[i]=1; } for(int i=1;i<=n;i++) if(ans[i]) printf("NO\n"); else printf("YES\n"); return 0;}
luogu P3144 [USACO16OPEN]關閉農場Closing the Farm_Silver解題報告