AcWing 3587. 连通图
原题链接
简单
作者:
来罐达芬奇
,
2024-12-10 15:33:58
,
所有人可见
,
阅读 5
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
const int N = 1010;
vector<int> q[N];
int n,m;
bool st[N];
void inputData()
{
memset(q,0,sizeof q);
memset(st, false, sizeof st);
for(int i=0;i<m;i++)
{
int a,b;
cin>>a>>b;
q[a].push_back(b);
q[b].push_back(a);
}
}
void dfs(int u)
{
st[u] = true;
for(auto t : q[u])
if(!st[t])
dfs(t);
}
bool judge_dfs()
{
inputData();
bool flag = true;
dfs(1);
for(int i=1;i<=n;i++)
{
if(!st[i])
{
flag = false;
break;
}
}
return flag;
}
bool judge_bfs()
{
inputData();
st[1] = true;
int que[N];
int hh = 0, tt = -1;
que[++tt] = 1;
while(hh <= tt)
{
int t = que[hh++];
for(auto i : q[t])
if(!st[i])
{
que[++tt] = i;
st[i] = true;
}
}
return hh == n;
}
int p[N];
int find(int x)
{
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
bool judge_union_find()
{
memset(p,0,sizeof p);
for(int i=1;i<=n;i++) p[i] = i;
for(int i=1;i<=m;i++)
{
int a,b;
cin>>a>>b;
int pa = find(a), pb = find(b);
if(pa != pb)
p[pa] = pb;
}
int r = find(1);
bool flag = true;
for(int i=1;i<=n;i++)
if(find(i) != r)
{
flag = false;
break;
}
return flag;
}
int main()
{
while(cin>>n>>m)
{
if(judge_union_find()) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}