标签:des style blog java color strong
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3105 Accepted Submission(s): 1330
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <iostream> 5 #define N 100005 6 using namespace std; 7 8 9 struct node{ 10 int l, r; 11 int dis; 12 int val; 13 int f; 14 }tree[N]; 15 16 int findroot(int p); 17 int merge(int x,int y); 18 int del(int x); 19 void solve(int x,int y); 20 21 22 main() 23 { 24 int n, m, i, j, k; 25 while(scanf("%d",&n)==1){ 26 for(i=1;i<=n;i++){ 27 scanf("%d",&tree[i].val); 28 tree[i].l=tree[i].r=tree[i].dis=0; 29 tree[i].f=i; 30 } 31 int x, y; 32 scanf("%d",&m); 33 while(m--){ 34 scanf("%d %d",&x,&y); 35 int fx=findroot(x); 36 int fy=findroot(y); 37 if(fx==fy){ 38 printf("-1\n"); 39 continue; 40 } 41 solve(fx,fy); 42 } 43 } 44 } 45 46 int findroot(int p){ 47 int r=p; 48 while(r!=tree[r].f){ 49 r=tree[r].f; 50 } 51 return r; 52 } 53 54 int merge(int x,int y){ 55 if(x==0) return y; 56 if(y==0) return x; 57 if(tree[x].val<tree[y].val) swap(x,y); 58 tree[x].r=merge(tree[x].r,y); 59 tree[tree[x].r].f=x; 60 if(tree[tree[x].r].dis>tree[tree[x].l].dis) swap(tree[x].l,tree[x].r); 61 if(!tree[x].r) tree[x].dis=0; 62 else tree[x].dis=tree[tree[x].r].dis+1; 63 return x; 64 } 65 66 int del(int x){ 67 int left=tree[x].l; 68 int right=tree[x].r; 69 tree[left].f=left; 70 tree[right].f=right; 71 tree[x].l=tree[x].r=tree[x].dis=0; 72 return merge(left,right); 73 } 74 75 void solve(int x,int y){ 76 tree[x].val/=2; 77 tree[y].val/=2; 78 int left=del(x); 79 int right=del(y); 80 left=merge(left,x); 81 right=merge(right,y); 82 int num=merge(left,right); 83 printf("%d\n",tree[num].val); 84 }
HDU 1512 并查集+左偏树,布布扣,bubuko.com
标签:des style blog java color strong
原文地址:http://www.cnblogs.com/qq1012662902/p/3849456.html