Tag: and query set
After one morning, I finally AC Wa and forgot to have a ring !!!
I used and checked the knowledge and reviewed it again !!
Train of Thought: after entering the information, you can find out whether it can form a ring. If there are two parent nodes or not, you can find the relevant ancestor;
Note: if there is only one node, it is also a tree. If there are two or more root nodes, it is not a tree. If there is no root node, It is not
Link http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1325
Code
# Include <stdio. h> int fat [1000]; int father (int n) // search for the ancestor {If (fat [N]! = N) fat [N] = Father (fat [N]); Return fat [N];} int main () {int I, j, n, m, A [1000], B [1000], V = 1; while (1) {for (I = 0; I <1000; I ++) fat [I] = I; int flag = 0; scanf ("% d", & A [0], & B [0]); if (A [0] <0 & B [0] <0) break; fat [B [0] = A [0]; // The question shows fat [B [I] = A [I]; I = 1; while (scanf ("% d", & A [I], & B [I]), a [I] | B [I]) {If (flag = 0) {// If flag = 1, the ring is displayed, or two parent nodes, if (fat [A [I] = B [I]) {flag = 1; // determine if it is a loop continue;} If (fat [B [I]! = B [I]) {flag = 1; // determine if two parent nodes exist;} If (fat [A [I]! = A [I]) fat [A [I] = Father (A [I]); fat [B [I] = A [I];} else {fat [B [I] = A [I];} I ++;} For (j = 0; j <I ;++ J) // determine whether there are any ancestor (root node) if (fat [A [J] = A [J]) break; if (I = J) Flag = 1; if (FLAG) {printf ("case % d is not a tree. \ n ", V ++); continue;} else {if (I = 1) {// if there is only one set of printf (" case % d is a tree. \ n ", V ++); continue;} For (j = 1; j <I; ++ J) // determine if there are multiple root nodes if (fat [A [J]! = Fat [A [0]) {printf ("case % d is not a tree. \ n ", V ++); break;} If (j = I) printf (" case % d is a tree. \ n ", V ++) ;}} return 0 ;}