洛谷3521 [poi2011]rot Tree rotations

启发式合并总是很神仙

Posted by yjjr's blog on November 5, 2018

code

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define ll long long
#define mem(x,num) memset(x,num,sizeof x)
#define reg(x) for(int i=last[x];i;i=e[i].next)
using namespace std;
ll f=1,x=0;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int maxn=4e5+6,maxm=4e6+6;
int n,Size,seg,v[maxn],l[maxn],r[maxn],root[maxn];
int sum[maxm],ls[maxm],rs[maxm];
ll ans,cnt1,cnt2;
if(!v[x]){
l[x]=++Size;
r[x]=++Size;
}
}
void pushup(int k){sum[k]=sum[ls[k]]+sum[rs[k]];}
void build(int &k,int l,int r,int val){
#define mid ((l+r)>>1)
if(!k)k=++seg;
if(l==r){sum[k]=1;return;}
if(val<=mid)build(ls[k],l,mid,val);else build(rs[k],mid+1,r,val);
pushup(k);
}
inline int merge(int x,int y){
if(!x)return y;
if(!y)return x;
cnt1+=(ll)sum[rs[x]]*sum[ls[y]];
cnt2+=(ll)sum[ls[x]]*sum[rs[y]];
ls[x]=merge(ls[x],ls[y]);
rs[x]=merge(rs[x],rs[y]);
pushup(x);
return x;
}
void solve(int x){
if(!x)return;
solve(l[x]);solve(r[x]);
if(!v[x]){
cnt1=cnt2=0;
root[x]=merge(root[l[x]],root[r[x]]);
ans+=min(cnt1,cnt2);
}
}
int main()
{