**
洛谷oj:P3144 Closing the Farm S
**
#题目描述
#这个输出可以一起输出的 不是一输入一输出
#想想 这个可以看成是在开启农场 你正着看要你找开启的联通块 你要关农场
反着看 你从没有农场到开农场 找的也是开启的连通块 找的东西是一样的(要理解)!
#知识点
并查集
#代码
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
int pcj[3100],exist[3100],x[3100],y[3100],store[3100],ans[3100];
//!pcj 并查集 exist是否存在并查集中 1 yes 0 no x,y,store存储数据 ans 结果集
int n,m;
int Find(int x)
{
if(x != pcj[x])
{
pcj[x] = Find(pcj[x]);
}
return pcj[x];
}
void Union(int x,int y)
{
int rx = Find(x);
int ry = Find(y);
if(rx == ry)
{
return ;
}else
{
pcj[rx] = ry;
}
}
int main()
{
cin >> n >> m;
for(int i=1;i<=m;i++)
{
cin >> x[i] >> y[i];
}
for(int i=1;i<=n;i++)
{
cin >> store[i];
}
//初始化
for(int i=0;i<=n;i++)
{
pcj[i] = i;
exist[i] = 0;
ans[i] = 0;
}
for(int i=n;i>=1;i--)
{
exist[store[i]] = 1;//! 将一个点置入并查集
for(int j=1;j<=m;j++)
{
if(exist[x[j]] == 1 && exist[y[j]] == 1)//!如果这俩个点都在并查集中 就连接 也可以理解成减少根节点的数量
{
Union(x[j],y[j]);
}
}
for(int j=1;j<=n;j++)
{
if(j == pcj[j] && exist[j] == 1)//在并查集中 且 是根节点
{
ans[i] ++;
}
}
}
for(int i=1;i<=n-1;i++)
{
if(ans[i] == 1)
{
cout << "YES" <<endl;
}else
{
cout << "NO" <<endl;
}
}
cout << "YES" <<endl;//最开始时是联通的
return 0;
}
#总结
第一次遇到这种题就懵了 看题解也看不懂 还是要多多理解 懂了都懂 HaHa
可以看看 星球大战 一样题型 那个特殊点