web123456

Determine whether a graph is a tree (directed graph and undirected graph)

#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<bitset> #include<queue> using namespace std; typedef long long ll; typedef pair<int,int> PII; const int N = 200007, M = 5000007, INF = 0x3f3f3f3f; int fa[N], n, m; bool vis[N]; int Find(int x) { if(fa[x] == x)return x; return fa[x] = Find(fa[x]); } bool unions(int x, int y) { int fx = Find(x); int fy = Find(y); if(fx != fy){ fa[fy] = fx;//Note that the merged point is the original point return true; } return false;//There are rings, not trees } int x, y; int kcase; int main() { while(scanf("%d%d", &x, &y)){ kcase ++ ; bool flag = true; if(x < 0 || y < 0) break; if(x == 0 && y == 0){ printf("Case %d is a tree.\n", ++ kcase); continue; } for(int i = 1; i < N; ++ i){ fa[i] = i; vis[i] = 0; } while(!(x == y && y == 0)){ vis[x] = true; vis[y] = true; //! Because the tree has only one edge pointing to the node, and the root has no edge pointing to the root node, so if there are two or more edges pointing to it, it means that it is not a tree if(Find(y) != y) flag = false; else if(unions(x, y) == 0){//There are rings, not trees flag = false; } scanf("%d%d", &x, &y); } int tot = 0; for(int i = 1; i < N; ++ i){ if(vis[i] && fa[i] == i)// Find a few roots tot ++ ; /*if(tot > 1){ flag = 1; break; }*/ } if(tot != 0 && tot != 1)flag = false; //cout << tot << "ok" <<endl; //The entry level is greater than 1 or it is a forest if(flag) printf("Case %d is a tree.\n", kcase); else printf("Case %d is not a tree.\n", kcase); } return 0; }