Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=1232
Analysis: The essence of the subject is a and check the set of problems, Ah, and check set is not very understanding, began to do not know what method to do. The problem of dynamic connectivity is also found in general use and solution. The key is to find out the number of isolated points, the number of roads to be built is the number of isolated points-1. There is the result of the output, you should pay attention to how to input.
and 3 main operations of the collection: Get the root, merge two nodes in the collection, query two nodes are in the same collection
1#include <iostream>2#include <cstdio>3 using namespacestd;4 intfather[1007];5 voidInit ()6 { 7 inti;8 for(i=1;i<1007; i++)9father[i]=i;Ten } One intFintN) A { - if(n!=Father[n]) -father[n]=f (father[n]); the returnFather[n]; -}//Get root node - voidMergeintXinty) - { + intFx,fy; -fx=f (x); +fy=f (y); A if(fx!=fy) atfather[fx]=fy; - } - intMain () - { - intn,m,a,b; - while(~SCANF ("%d",&N), N) in { -scanf"%d",&m); toInit ();//don't forget to initialize + for(intI=1; i<=m;i++) - { thescanf"%d%d",&a,&b); * merge (A, b); $ }Panax Notoginseng intcns=0; - for(intj=1; j<=n;j++) the { + if(FATHER[J]==J)//find out the number of isolated points Acns++; the } +printf"%d\n", cns-1); - } $ $ return 0; -}
View Code
B-unblocked Project