[可并堆] BZOJ 1078 [SCOI2008]斜堆

来源:互联网 发布:mac jenkins android 编辑:程序博客网 时间:2024/05/18 02:04

Orz mato大神的题解:http://www.cppblog.com/MatoNo1/archive/2012/10/07/192131.html


实际上这道题并没有要写可并堆,只是考察了斜堆的性质


斜堆是可合并堆的一种实现形式,其更稳定的实现是左偏树(斜堆只能做到均摊logN,而左偏树则可以严格做到每次操作O(logN))。
斜堆最典型的特点,上面已经说过了,如果一个结点没有左子树,那么它也一定没有右子树。这样,大多数斜堆看上去是往左倾斜的(这也就是它的名字的由来……)。如果给每个结点加上一个距离值dist[],为该结点到它最近的没有右子树的子结点的距离,并且满足任意结点的左子结点的距离值都不小于右子结点的距离值的话,就成了左偏树


#include<cstdio>#include<cstdlib>#include<cstring>#include<algorithm>using namespace std;inline char nc(){static char buf[100000],*p1=buf,*p2=buf;if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }return *p1++;}inline void read(int &x){char c=nc(),b=1;for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;}int n,rt;int l[105],r[105],fat[105];int pnt,lst[105];void Solve(){int x=rt;while (r[x]!=-1) x=l[x];if(l[x]!=-1 && l[l[x]]==-1 && r[l[x]]==-1) x=l[x];lst[++pnt]=x;if(x==rt) rt=l[rt];int f=fat[x];if (f!=-1) l[f]=l[x],fat[l[f]]=f;while (f!=-1) swap(l[f],r[f]),f=fat[f];}int main(){freopen("t.in","r",stdin);freopen("t.out","w",stdout);int x,f;fat[0]=-1; memset(l,-1,sizeof(l)); memset(r,-1,sizeof(r));read(n);for(int i=1;i<=n;i++){read(x);if(x<100)l[x]=i,fat[i]=x;elser[x-100]=i,fat[i]=x-100;}for(int i=1;i<=n+1;i++){x=rt;while (r[x]!=-1) x=l[x];if(l[x]!=-1 && l[l[x]]==-1 && r[l[x]]==-1) x=l[x];lst[++pnt]=x;if(x==rt) rt=l[rt];f=fat[x];if (f!=-1) l[f]=l[x],fat[l[f]]=f;while (f!=-1) swap(l[f],r[f]),f=fat[f];}for (int i=pnt;i;i--) printf("%d ",lst[i]);return 0;}


0 0