题意:判断一个图是否为连通无环图
思路:判断是否为连通无环图
1,无环,判断输入边的两个端点,如果它们有同一个父节点,则证明有环
2,连通,整个图只有一个集合
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <ctime>
#include <cmath>
#include <cctype>
using namespace std;
#define maxn 100005
#define LL long long
int cas=1,T;
int pre[100005];
int vis[100005];
int Find(int x)
{
int r = x;
while (r!=pre[r])
r=pre[r];
int i = x,j;
while (pre[i]!=r)
{
j=pre[i];
pre[i]=r;
i=j;
}
return r;
}
void mix(int x,int y)
{
int fx = Find(x),fy=Find(y);
if (fx!=fy)
{
pre[fy]=fx;
}
}
int main()
{
//freopen("in","r",stdin);
int a,b;
while (scanf("%d%d",&a,&b)!=EOF)
{
if (a== -1 && b==-1)
break;
if (!a && !b)
{
puts("Yes");
continue;
}
for (int i = 1;i<=maxn;i++)
{
pre[i]=i;
vis[i]=0;
}
mix(a,b);
vis[a]=1;
vis[b]=1;
int flag = 1;
while (scanf("%d%d",&a,&b))
{
if (!a && !b)
break;
if (Find(a)==Find(b))
flag=0;
else
mix(a,b);
vis[a]=1;
vis[b]=1;
}
if (!flag)
puts("No");
else
{
for (int i = 1;i<=maxn;i++)
if (vis[i] && pre[i]==i)
flag++;
if (flag == 2)
puts("Yes");
else
puts("No");
}
}
//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
return 0;
}