Question: give you some directed edges (endpoint, with a length of 1) to determine whether the given graph is a tree.
Analysis: Graph Theory, and query sets. A tree is a directed acyclic graph (Forest is not connected) connected to all vertices ).
You can determine whether a ring exists according to the definition of the tree. There are two types of rings:
1. chain rings; 2. There are nodes with multiple Father's Day points;
In both cases, you only need to use and check the set to determine whether there is a number of sets before merging,
In a unified set, this edge must form a ring;
Note that the decision cannot be a forest.
Note: accuracy is a problem that has no data scope.
#include <iostream>#include <cstdlib> #include <cstdio>using namespace std;int used[100001];int sets[100001],rank[100001];int set_root(int a){if (a != sets[a])sets[a] = set_root(sets[a]);return sets[a];}int main(){int a,b,t = 1;while (~scanf("%d%d",&a,&b) && a >= 0 && b >= 0) {for (int i = 0 ; i < 100000 ; ++ i) {sets[i] = i;used[i] = rank[i] = 0;}int flag = 1;while (a||b) {if (set_root(a) == set_root(b))flag = 0;if (flag) {used[a] = used[b] = 1;sets[set_root(b)] = set_root(a);}scanf("%d%d",&a,&b);}if (flag == 1) {int count = 0;for (int i = 0 ; i < 100000 ; ++ i)if (used[i] && set_root(i) == i)if (count ++) {flag = 0;break;}}if (flag == 0)printf("Case %d is not a tree.\n",t ++);else printf("Case %d is a tree.\n",t ++);}return 0;}
Is it a tree?