题目链接
解题思路
需要判断图是否连通 且 只有一个连通分量
注意只有0 0的情况。
代码
#include#include #define SET_SIZE 100010int s[SET_SIZE];bool vis[SET_SIZE];void MakeSet(int n){ for(int i=1; i<=n; i++) s[i] = i;}int FindFather(int x){ if(s[x] != x) s[x] = FindFather(s[x]); return x;}void UnionSet(int fx, int fy){ s[fx] = fy;}int main(){ int x, y; scanf("%d%d", &x, &y); while(!(x == -1 && y == -1)) { bool flag = false; int count = 0; int vNum = 0, edgeNum = 0; MakeSet(SET_SIZE); memset(vis, 0, sizeof(vis)); while(!(x == 0 && y == 0)) { count++; if(!vis[x]) { vNum++; vis[x] = true; } if(!vis[y]) { vNum++; vis[y] = true; } if(!flag) { int fx = FindFather(x); int fy = FindFather(y); if(fx == fy) flag = true; else { UnionSet(fx, fy); edgeNum++; } } scanf("%d%d", &x, &y); } if(count == 0) printf("Yes\n"); else{ if(!flag && vNum == edgeNum + 1) printf("Yes\n"); else printf("No\n"); } scanf("%d%d", &x, &y); } return 0;}