标签:
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4714 Accepted Submission(s): 2032
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 using namespace std; 5 const int maxn=100010; 6 int ch[maxn][2],dis[maxn],key[maxn]; 7 int fa[maxn],rt[maxn],n,m; 8 void Init(){ 9 dis[0]=-1; 10 for(int i=0;i<=n;i++){ 11 fa[i]=i;rt[i]=i;dis[i]=0; 12 ch[i][0]=ch[i][1]=0; 13 } 14 } 15 16 int Merge(int x,int y){ 17 if(!x||!y)return x|y; 18 if(key[x]<key[y])swap(x,y); 19 ch[x][1]=Merge(ch[x][1],y); 20 if(dis[ch[x][1]]>dis[ch[x][0]]) 21 swap(ch[x][0],ch[x][1]); 22 dis[x]=dis[ch[x][1]]+1; 23 return x; 24 } 25 26 void Delete(int x){ 27 int tmp=rt[x]; 28 rt[x]=Merge(ch[rt[x]][0],ch[rt[x]][1]); 29 ch[tmp][0]=ch[tmp][1]=0; 30 } 31 32 int Find(int x){ 33 return x==fa[x]?x:fa[x]=Find(fa[x]); 34 } 35 36 int main(){ 37 while(scanf("%d",&n)!=-1){ 38 Init(); 39 for(int i=1;i<=n;i++) 40 scanf("%d",&key[i]); 41 int x,y; 42 scanf("%d",&m); 43 while(m--){ 44 scanf("%d%d",&x,&y); 45 x=Find(x);y=Find(y); 46 if(x==y) 47 printf("-1\n"); 48 else{ 49 int ta=rt[x],tb=rt[y]; 50 Delete(x);key[ta]/=2;rt[x]=Merge(rt[x],ta); 51 Delete(y);key[tb]/=2;rt[y]=Merge(rt[y],tb); 52 fa[y]=x;rt[x]=Merge(rt[x],rt[y]); 53 printf("%d\n",key[rt[x]]); 54 } 55 } 56 } 57 return 0; 58 }
数据结构(左偏树):HDU 1512 Monkey King
标签:
原文地址:http://www.cnblogs.com/TenderRun/p/5612123.html