• 洛谷P1196 [NOI2002]银河英雄传说 并查集


     1 #include<cstdio>
     2 #include<cstring>
     3 
     4 using namespace std;
     5 
     6 int find(int);
     7 int abs(int);
     8 void setup();
     9 
    10 int fa[30005];
    11 int size[30005];
    12 int d[30005];
    13 int T,x,y,fx,fy;
    14 char f;
    15 
    16 int main(){
    17     setup();
    18     scanf("%d",&T);
    19     for(int i=1;i<=T;i++){
    20         do{
    21             f=getchar();
    22         }while(f!='M' && f!='C');
    23         scanf("%d%d",&x,&y);
    24         fx=find(x);
    25         fy=find(y);
    26         if(f=='C'){
    27             if(fx==fy)printf("%d
    ",abs(d[x]-d[y])-1);
    28             else printf("-1
    ");
    29         }
    30         else{
    31             fa[fx]=fy;
    32             d[fx]=size[fy];
    33             size[fy]+=size[fx];
    34         }
    35     }
    36     
    37     return 0;
    38 }
    39 
    40 int find(int x){  //无需处理size 
    41     if(fa[x]==x)return x;
    42     else{
    43         int gf=find(fa[x]);
    44         d[x]+=d[fa[x]];
    45         return fa[x]=gf;
    46     }
    47 }
    48 
    49 int abs(int x){
    50     if(x<0)return -x;
    51     else return x;
    52 }
    53 
    54 void setup(){
    55     for(int i=1;i<=30000;i++){
    56         fa[i]=i;
    57         size[i]=1;
    58         d[i]=0;
    59     }
    60 }
  • 相关阅读:
    PHP中的NULL类型
    js中自定义事件,使用了jQuery
    chrome调试文章
    codeforces 633D
    hdu 1496 Equations
    poj 1286 Necklace of Beads
    poj 2154 Color
    poj 3270 Cow Sorting
    poj 1026 Cipher
    poj 2369 Permutations
  • 原文地址:https://www.cnblogs.com/running-coder-wfh/p/11336691.html
Copyright © 2020-2023  润新知