***题意就是判断图是否连通和是否有回路
思路:判断连通性可以看整张图有几个根节点,回路的判断可以看输入的两个节点是否是同一根节点,若是就有回路***
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<cctype> #include<queue> #include<vector> #include<algorithm> using namespace std; typedef long long LL; #define N 1001000 #define INF 0x3f3f3f int father[N], vis[N], flag; int Find(int x) { while(x!=father[x]) x=father[x]; return x; } int main() { int a, b; while(scanf("%d%d", &a, &b), a!=-1 || b!=-1) { if(a==0&&b==0) { printf("Yes "); continue; } for(int i=1; i<N; i++) father[i]=i; memset(vis, 0, sizeof(vis)); flag=1; vis[a]=vis[b]=1; int x=Find(a); int y=Find(b); if(x!=y) father[x]=y; else flag=0; while(scanf("%d%d", &a, &b), a || b) { vis[a]=vis[b]=1; int x=Find(a); int y=Find(b); if(x!=y) father[x]=y; else flag=0; } int k=0; if(flag) { for(int i=1; i<N; i++) { if(vis[i]&&father[i]==i) k++; if(k>1) { flag=0; break; } } } if(flag) printf("Yes "); else printf("No "); } return 0; }