In addition to the empty tree, the tree has only one root node. Besides the root node, the other nodes have only one precursor.
To determine whether a graph is a tree, you need to determine whether there is only one common ancestor, and the inbound degree is less than 2, and the ring cannot be formed.
Link: poj 1308
# Include <stdio. h> # define n 100000int f [n + 10], t [n + 10], C [n + 10]; int find (int A) {if (! = F [a]) f [a] = find (F [a]); Return f [a];} int mix (int A, int B) {int X, y; X = find (a); y = find (B); If (x = y) return 0; F [x] = y; return 1 ;} int main () {int I, j = 0, n, m, a, B, flag; while (scanf ("% d", & M, & N )! = EOF) {If (M <0 & n <0) // terminate break when two negative numbers are input; j ++; if (M = 0 & n = 0) {printf ("case % d is a tree. \ n ", J); continue;} for (I = 1; I <= N; I ++) {f [I] = I; c [I] = T [I] = 0;} flag = 1; while (M! = 0 & n! = 0) {T [m] = T [N] = 1; C [N] ++; // calculate the inbound degree if (C [N]> 1) flag = 0; A = mix (m, n); // determine whether the ring is formed if (! A) Flag = 0; scanf ("% d", & M, & N) ;}if (FLAG) {B = 0; for (I = 1; I <= N; I ++) {If (T [I] & F [I] = I) B ++; // calculate the number of root nodes if (B> 1) break;} If (flag & B = 1) printf ("case % d is a tree. \ n ", J); else printf (" case % d is not a tree. \ n ", J);} return 0 ;}