本文主要是介绍洛谷P3144 [USACO16OPEN]关闭农场Closing the Farm_Silver(并查集),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
展开
题目描述
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 3
1 2
2 3
3 4
3
4
1
2
输出 #1复制
YES
NO
YES
YES
思路: 并查集维护集和大小,再逆序插点就好了。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>using namespace std;const int maxn = 3e5 + 7;int fa[maxn],ans[maxn],sizee[maxn],vis[maxn];
int head[maxn],nex[maxn],to[maxn],a[maxn],tot;
int maxx;void add(int x,int y)
{to[++tot] = y;nex[tot] = head[x];head[x] = tot;
}int findset(int x)
{if(fa[x] == x)return x;return fa[x] = findset(fa[x]);
}void Union(int x,int y)
{int rx = findset(x),ry = findset(y);if(rx != ry){if(sizee[ry] < sizee[rx])swap(rx,ry);sizee[ry] += sizee[rx];maxx = max(sizee[ry],maxx);fa[rx] = ry;}
}int main()
{int n,m;scanf("%d%d",&n,&m);for(int i = 1;i <= n;i++){sizee[i] = 1;fa[i] = i;}for(int i = 1;i <= m;i++){int x,y;scanf("%d%d",&x,&y);add(x,y);add(y,x);}for(int i = 1;i <= n;i++){scanf("%d",&a[i]);}maxx = 1;for(int i = n;i >= 1;i--){int x = a[i];vis[x] = 1;for(int j = head[x];j;j = nex[j]){int y = to[j];if(!vis[y])continue;Union(x,y);}if(maxx == n - i + 1)ans[i] = 1;}for(int i = 1;i <= n;i++){if(ans[i] == 1)printf("YES\n");else printf("NO\n");}return 0;
}
这篇关于洛谷P3144 [USACO16OPEN]关闭农场Closing the Farm_Silver(并查集)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!