PAT 1013 Grade solution to a problem - disjoint-set path compression +

Topic analysis:

This problem is preliminary browser template entitled to know the title disjoint-set data input N ranges from 1 to 1000, M is the range of 0 to 2 ^ 1000, through the structure of each record of the connection relation, P [] array with the record of each node, for k queries, each time re-maintenance p [] array, and each must exclude the difference is that the node is re-occupied maintain links relationship p [] array of nodes, and eventually number -2 answer is set (the set of the occupation must be separate points, n requires n-1 sets can be connected to the edges)

 1 #include<iostream>
 2 using namespace std;
 3 
 4 struct Node{
 5     int from;
 6     int to;
 7 }a[1000005];
 8 int p[1005];
 9 int n, m, k;
10 
11 int find(int x){
12     int y = x;
13     while(p[x] != x){
14         x = p[x];
15     }
16     // path compressor case x is a root 
. 17      the while (P [y] =! {X)
 18 is          int T = y;             // for each y node on the path to be reserved bit 
. 19          y P = [y];             / / in this case we still in the above order to query the root 
20 is          p [t] = X;             // y has become the p [y] values, and t is recorded before the values of y and p [previous y] has less than, and its path will be compressed, it becomes directly with the X 
21 is      }
 22 is      return X;
 23 is  }
 24  
25  void of Union ( int X, int Y) {
 26 is      int FX = Find (X);
 27      int FY =Find (Y);
 28      IF (FX =! FY) {
 29          P [FX] = FY;
 30      }    
 31 is  }
 32  
33 is  void the init ( int Occupy) {
 34 is      for ( int I = . 1 ; I <= n-; I ++) P [I] = I;
 35      for ( int I = . 1 ; I <= m; I ++ ) {
 36          // maintenance disjoint-set bearing in mind the city occupied in accordance with a relation of one to one is not involved 
37          IF (A [I]. from ! && Occupy = A [I] .to! = Occupy) {
 38 is              of Union (A [I].from, a[i].to);
39         }
40     }
41 }
42 
43 void run(){
44     int ans = 0;
45     for(int i = 1; i <= n; i++){
46         if(p[i] == i){
47             ans++;
48         }
49     }    
50     printf("%d\n", ans - 2);
51 } 
52 
53 int main(){
54     while(scanf("%d%d%d", &n, &m, &k) != EOF){
55         for(int i = 1; i <= m; i++){
56             scanf("%d%d", &a[i].from, &a[i].to);            
57         }
58         int occupy; 
59         for(int i = 1; i <= k; i++){
60             scanf("%d", &occupy);
61             // every time the initialization disjoint-set 
62 is              the init (Occupy);
 63 is              // Get the line number to be added each time at least 
64              RUN ();
 65          }
 66      }
 67      return  0 ;
 68 }

 

Guess you like

Origin www.cnblogs.com/findview/p/11666697.html