左偏树

模板题(HDU1512):

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 #include<cstring>
 5 #include<cmath>
 6 #include<cstdlib>
 7 #include<vector>
 8 using namespace std;
 9 typedef long long ll;
10 typedef long double ld;
11 typedef pair<int,int> pr;
12 const double pi=acos(-1);
13 #define rep(i,a,n) for(int i=a;i<=n;i++)
14 #define per(i,n,a) for(int i=n;i>=a;i--)
15 #define Rep(i,u) for(int i=head[u];i;i=Next[i])
16 #define clr(a) memset(a,0,sizeof(a))
17 #define pb push_back
18 #define mp make_pair
19 #define fi first
20 #define sc second
21 #define pq priority_queue
22 #define pqb priority_queue <int, vector<int>, less<int> >
23 #define pqs priority_queue <int, vector<int>, greater<int> >
24 #define vec vector
25 ld eps=1e-9;
26 ll pp=1000000007;
27 ll mo(ll a,ll pp){if(a>=0 && a<pp)return a;a%=pp;if(a<0)a+=pp;return a;}
28 ll powmod(ll a,ll b,ll pp){ll ans=1;for(;b;b>>=1,a=mo(a*a,pp))if(b&1)ans=mo(ans*a,pp);return ans;}
29 void fre() { freopen("c://test//input.in", "r", stdin); freopen("c://test//output.out", "w", stdout); }
30 //void add(int x,int y,int z){ v[++e]=y; next[e]=head[x]; head[x]=e; cost[e]=z; }
31 int dx[5]={0,-1,1,0,0},dy[5]={0,0,0,-1,1};
32 ll read(){ ll ans=0; char last=' ',ch=getchar();
33 while(ch<'0' || ch>'9')last=ch,ch=getchar();
34 while(ch>='0' && ch<='9')ans=ans*10+ch-'0',ch=getchar();
35 if(last=='-')ans=-ans; return ans;
36 }
37 const int N=100005;
38 struct LH{
39     int v,l,r,f,dis;
40 }heap[N];
41 int n;
42 inline int getf(int x){
43     if (heap[x].f==x) return x;
44     else return getf(heap[x].f);
45 }
46 inline int Meg(int x,int y){
47     if (!x) return y; if (!y) return x;
48     if (heap[x].v<heap[y].v) swap(x,y);
49     heap[x].r=Meg(heap[x].r,y);
50     heap[heap[x].r].f=x;
51     if (heap[heap[x].l].dis<heap[heap[x].r].dis) swap(heap[x].l,heap[x].r);
52     if (heap[x].r==0) heap[x].dis=0;
53     else heap[x].dis=heap[heap[x].r].dis+1;
54     return x;
55 } 
56 inline int Del(int x){
57     int    L=heap[x].l,R=heap[x].r;
58     heap[L].f=L; heap[R].f=R;
59     heap[x].l=0; heap[x].r=0; heap[x].dis=0;
60     return Meg(L,R);
61 }
62 void Work(int ra,int rb){
63     heap[ra].v/=2; heap[rb].v/=2;
64     int ra_=Del(ra),rb_=Del(rb);
65     int a=Meg(ra_,ra),b=Meg(rb_,rb);
66     int ans=Meg(a,b);
67     printf("%d\n",heap[ans].v);
68 }
69 int main(){
70     while (~scanf("%d",&n)){
71         for (int i=1;i<=n;i++) heap[i].v=read(),heap[i].l=heap[i].r=heap[i].dis=0,heap[i].f=i;
72         int q=read();
73         while (q--){
74             int a=read(),b=read();
75             int fa_=getf(a),fb_=getf(b);
76             if (fa_!=fb_){
77                 Work(fa_,fb_);
78             } else puts("-1");
79         }
80     }
81     return 0;
82 } 
View Code

 

posted @ 2017-09-03 19:18  SXia  阅读(109)  评论(0编辑  收藏  举报