Building Block HDU - 2818 (並查集)
阿新 • • 發佈:2017-09-08
freopen return 記錄 scanf splay else 一次 == gif
Building Block
HDU - 2818
題意:搬磚。。。每一次可以把a所在的那一堆放到b所在的那一堆上面,問第x號磚下面有幾塊磚。
記錄一下到根節點的距離(dw),以及根節點上方有幾塊磚(up)。
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 const int maxn=30010; 5 int f[maxn],up[maxn],dw[maxn]; 6 7 int gf(int x){ 8 if(x==f[x]){ 9 return x; 10 } 11View Codeint r=f[x]; 12 f[x]=gf(r); 13 dw[x]+=dw[r]; 14 return f[x]; 15 } 16 17 int n; 18 int main(){ 19 // freopen("in.txt","r",stdin); 20 while(scanf("%d",&n)!=EOF){ 21 int ans=0; 22 for(int i=0;i<maxn;i++) {f[i]=i;up[i]=1;dw[i]=0;} 23 for(int i=0;i<n;i++){24 int a,b; 25 char c; 26 getchar(); 27 scanf("%c",&c); 28 if(c==‘M‘){ 29 scanf("%d%d",&a,&b); 30 int pa=gf(a),pb=gf(b); 31 if(pa!=pb){ 32 f[pa]=pb; 33 dw[pa]+=up[pb];34 up[pb]+=up[pa]; 35 } 36 }else{ 37 scanf("%d",&a); 38 gf(a); 39 printf("%d\n",dw[a]); 40 } 41 } 42 } 43 return 0; 44 }
Building Block HDU - 2818 (並查集)