Question link: https://icpcarchive.ecs.baylor.edu/index.php? Option = com_onlinejudge & Itemid = 8 & page = show_problem & problem = 4102
----------------------------------------------------------------------------------------------------------------------------------------------------------
Welcome to tianci Hut: http://user.qzone.qq.com/593830943/main
----------------------------------------------------------------------------------------------------------------------------------------------------------
A graph consists of a set of vertices and edges between pairs of vertices. two vertices are connected if there is a path (subset of edges) leading from one vertex to another, and a connected component is a maximal subset of vertices that are all connected to each other. A graph consists of one or more connected components.
A tree is a connected component without cycles, but it can also be characterized in other ways. For example, a tree consistingNVertices has exactlyN-1 edges. Also, there is a unique path connecting any pair of vertices in a tree.
Given a graph, report the number of connected components that are also trees.
Input
The input consists of a number of cases. Each case starts with two non-negative integersNAndM, SatisfyingN500 andMN(N-1)/2. This is followedMLines, each containing two integers specifying the two distinct vertices connected by an edge. No edge will be specified twice (or given again in a different order). The vertices are labeled 1N. The end of input is indicated by a line containingN=M=0.
Output
For each case, print one of the following lines depending on how many different connected components are trees (T> 1 below ):
CaseX: A forestTTrees.
CaseX: There is one tree.
CaseX: No trees.
XIs the case number (starting from 1 ).
Sample Input
6 31 22 33 46 51 22 33 44 55 66 61 22 31 34 55 66 40 0
Sample output
Case 1: A forest of 3 trees.Case 2: There is one tree.Case 3: No trees.
Question: Find several trees and pay special attention to the situation of multiple rings. The Code is as follows:
# Include <cstdio> int father [1017]; int C [1017]; // records whether int A, B, n, m, K; int I, J; int find (int x) {return x = Father [x]? X: Father [x] = find (father [x]);} void Union (int x, int y) {int F1 = find (X ); int F2 = find (y); If (C [F1] & C [F2]) // invalid input return; k --; If (F1! = F2) {If (C [F2]) // The Father [F1] = F2; elsefather [F2] = F1 ;} else if (F1 = F2) // mark {C [F1] = 1 ;}} void Init () {for (I = 1; I <= N; I ++) {FATHER [I] = I; C [I] = 0 ;}} int main () {int CAS = 0; while (scanf ("% d", & N, & M )! = EOF) {If (n = 0 & M = 0) break; Init (); k = N; for (I = 1; I <= m; I ++) {scanf ("% d", & A, & B); Union (a, B) ;}if (k> 1) printf ("case % d: a forest of % d trees. \ n ", ++ cas, k); else if (k = 1) {printf (" case % d: There is one tree. \ n ", ++ CAS);} else {printf (" case % d: no trees. \ n ", ++ CAS) ;}} return 0 ;}
Uvalive 6091-trees (query set)