1078: [SCOI2008]斜堆
Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 906 Solved: 504
[ Submit][ Status][ Discuss]
Description
斜堆(skew heap)是一种常用的数据结构。它也是二叉树,且满足与二叉堆相同的堆性质:每个非根结点的值
都比它父亲大。因此在整棵斜堆中,根的值最小。但斜堆不必是平衡的,每个结点的左右儿子的大小关系也没有任
何规定。在本题中,斜堆中各个元素的值均不相同。 在斜堆H中插入新元素X的过程是递归进行的:当H为空或者X
小于H的根结点时X变为新的树根,而原来的树根(如果有的话)变为X的左儿子。当X大于H的根结点时,H根结点的
两棵子树交换,而X(递归)插入到交换后的左子树中。 给出一棵斜堆,包含值为0~n的结点各一次。求一个结点
序列,使得该斜堆可以通过在空树中依次插入这些结点得到。如果答案不惟一,输出字典序最小的解。输入保证有
解。
Input
第一行包含一个整数n。第二行包含n个整数d1, d2, ... , dn, di < 100表示i是di的左儿子,di>=100表示i
是di-100的右儿子。显然0总是根,所以输入中不含d0。
Output
仅一行,包含n+1整数,即字典序最小的插入序列。
Sample Input
6
100 0 101 102 1 2
100 0 101 102 1 2
Sample Output
0 1 2 3 4 5 6
HINT
Source
http://www.cppblog.com/MatoNo1/archive/2013/03/03/192131.html
【代码】
//bzoj 1078 [SCOI2008]斜堆
#include<iostream>
#include<cstring>
#include<cstdio>
#define ll long long
#define M(a) memset(a,0,sizeof a)
#define fo(i,j,k) for(i=j;i<=k;i++)
using namespace std;
const int mxn=105;
int ans[mxn];
int n,m,top,root;
struct HEAP
{
int l,r,fa;
}h[mxn];
inline int read()
{
int x=0,f=1;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;
}
inline void work()
{
int x=root;
while(h[x].r) x=h[x].l;
if(h[x].l && !h[h[x].l].l) x=h[x].l;
ans[++top]=x;
if(x==root) root=h[x].l;
int fa=h[x].fa,son=h[x].l;
if(fa) h[fa].l=son;
if(son) h[son].fa=fa;
while(h[x].fa) x=h[x].fa,swap(h[x].l,h[x].r);
}
int main()
{
int i,j;
n=read();
root=1;
fo(i,1,n)
{
int fa=read();
if(fa>=100) h[fa-100+1].r=i+1,h[i+1].fa=fa-100+1;
else h[fa+1].l=i+1,h[i+1].fa=fa+1;
}
fo(i,1,n+1) work();
for(i=top;i;i--) printf("%d ",ans[i]-1);
return 0;
}