洛谷P3144 [USACO16OPEN]關閉農場Closing the Farm_Silver
洛谷P3144 [USACO16OPEN]關閉農場Closing the Farm_Silver
題目描述
FJ和他的奶牛們正在計劃離開小鎮做一次長的旅行,同時FJ想臨時地關掉他的農場以節省一些金錢。
這個農場一共有被用M條雙向道路連接的N個谷倉(1<=N,M<=3000)。為了關閉整個農場,FJ 計劃每一次關閉掉一個谷倉。當一個谷倉被關閉了,所有的連接到這個谷倉的道路都會被關閉,而且再也不能夠被使用。
FJ現在正感興趣於知道在每一個時間(這裏的“時間”指在每一次關閉谷倉之後的時間)時他的農場是否是“全連通的”——也就是說從任意的一個開著的谷倉開始,能夠到達另外的一個谷倉。註意自從某一個時間之後,可能整個農場都開始不會是“全連通的”。
輸入輸出格式
輸入格式:
The first line of input contains $N$ and $M$. The next $M$ lines each describe a
path in terms of the pair of barns it connects (barns are conveniently numbered
$1 \ldots N$). The final $N$ lines give a permutation of $1 \ldots N$
describing the order in which the barns will be closed.
輸出格式:
The output consists of $N$ lines, each containing "YES" or "NO". The first line
indicates whether the initial farm is fully connected, and line $i+1$ indicates
whether the farm is fully connected after the $i$th closing.
輸入輸出樣例
輸入樣例#1: 復制4 3 1 2 2 3 3 4 3 4 1 2輸出樣例#1: 復制
YES NO YES YES
代碼
題目大意:每次刪除一個點詢問剩下的點是否連通。
逆序並查集維護。
#include <cstdio> #include <cmath> #include <cstring> #include <iostream> #include <algorithm> using namespace std; int can[3001],n; int fa[3001]; int ans[3001],a[3001]; int h[3001],ne[6001],to[6001],fr[6001],en=0; inline void add(int a,int b) {ne[en]=h[a];to[en]=b;fr[en]=a;h[a]=en++;} inline int gf(int k) { if (fa[k]==k) return k; else return fa[k]=gf(fa[k]); } int main() { memset(h,-1,sizeof h); int n,m; scanf("%d%d",&n,&m); for (int i=1;i<=m;++i) { int a,b; scanf("%d%d",&a,&b); add(a,b); add(b,a); } for (int i=1;i<=n;++i) scanf("%d",&a[i]),fa[i]=i; for (int i=n;i>=1;--i) { can[a[i]]=1; for (int j=h[a[i]];j>=0;j=ne[j]) { if (can[fr[j]]&&can[to[j]]) { int l=fr[j],r=to[j]; int fl=gf(l),fr=gf(r); if (fl!=fr) fa[fl]=fr; } } int cnt=0; for (int j=1;j<=n;++j) if (can[j]&&fa[j]==j) cnt++; if (cnt==1) ans[i]=1; } printf("YES\n"); for (int i=2;i<=n;++i) if (ans[i]) printf("YES\n"); else printf("NO\n"); }
洛谷P3144 [USACO16OPEN]關閉農場Closing the Farm_Silver