题解 | #连通图#
连通图
https://www.nowcoder.com/practice/569e89823a5141fe8a11ab7d4da21edf
#include <iostream>
using namespace std;
int father[1001];
int height[1001];
void Initial(int n)
{
for(int i=1;i<=n;i++)
{
father[i]=i;
height[i]=0;
}
}
//两树合并为同一集合
void Union(int a,int b)
{
a=father[a];
b=father[b];
if(father[a]!=father[b])
{
if(height[a]>height[b])father[b]=a;
else if(height[a]<height[b])father[a]=b;
else
{
father[a]=b;
height[b]++;
}
}
}
//找该树的根节点
int Find(int i)
{
if(i==father[i])return i;
else
return Find(father[i]);
}
int main() {
int n,m;
while (cin >> n>>m) {
if(n==0&&m==0)break;
Initial(n);
for(int i=1;i<=m;i++)
{
int a,b;cin>>a>>b;
Union(a,b);
}
int answer=0;
for(int i=1;i<=n;i++)
{
if(i==Find(i))answer++;
}
if(answer==1)cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}
