This topic design to a point of knowledge of the graph theory, fortunately I have learned the graph theory.
The idea is this:
When there are road connections between the two cities, the two cities are added to the same connected subset, and any two cities in each connected subset can be connected.
For example, there are two paths (2,3), then to join a connected subset of s, s = {1,2},2,3 also added to a connected subset, because 2 is already in S, then add 3 to S, s={1,2,3}, according to s we can conclude that 1 and 3 can be connected.
After all the roads have been processed, we get J connected subsets, so that each city can be connected, that is, J connected subsets can be connected, at least the j-1 edge is required, and a J connected subset is strung together.
I use arrays to implement connected subsets.
Java code:
ImportJava.util.*; Public classmain{ Public Static voidMain (String args[]) {Scanner in=NewScanner (system.in); while(In.hasnext ()) {intn =In.nextint (); if(n = = 0) Break; intm =In.nextint (); intFa[] =New int[N+1]; For simulating connected subsetsintVist[] =New int[N+1]; Number//initialization for statistical connected subsets
for(inti = 0; I <= N; i++) {Fa[i]=i; Vist[i]= 0; }
To handle every route . while(m--> 0){ intA =In.nextint (); intb =In.nextint (); Merge (A,B,FA); }
Because the result of find (I,FA) is the identity of the connected subset, the number of connected subsets, the number of vist arrays is 1 for(inti = 1; I <= N; i++) {Vist[find (I,FA)]= 1; } intCount = 0;
Count the number of connected subsets for(inti = 1; I <= N; i++){ if(Vist[i] = = 1) Count++; } System.out.println (Count-1); } in.close (); }
A and B are added to the same connected subset, and the connected subset is identified with the value of fa[b]. Each connected subset has a unique identity.
For each element I in a connected subset, when you call Find (I,FA), you will eventually get the identity. Public Static voidMergeintAintBintfa[]) {a=find (A,FA); b=find (B,FA); Fa[a]=Fa[b]; }
Finding the identity of x recursively Public Static intFindintXintfa[]) { if(x = = Fa[x])returnx; Else returnfind (FA[X],FA); }}
Nine degree OJ platform exercises--topic 1012