Bzoj1078 [scoi2008]斜堆


本文总阅读量
Posted by yjjr's blog on December 16, 2017

标签:可并堆

题目

题目传送门

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 Sample Output 0 1 2 3 4 5 6

分析

逆思维操作,按照题目中叙述的反着做

  1. 找到当前插入的节点(极左的节点)
  2. 删掉该点
  3. 把它的祖先的左右子树都交换了

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 mem(x,num) memset(x,num,sizeof x)
#define ll long long
using namespace std;
inline ll read()
{
	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=1e2+6;
struct tree{int l,r,fa;}t[maxn<<1];
int n,ans[maxn],root=1;
void find(int x,int now)
{
	if((!t[x].l&&!t[x].r)||(t[x].l&&!t[x].r&&(t[t[x].l].l)))
	{
		t[t[x].fa].l=t[x].l;
		if(t[x].l)t[t[x].l].fa=t[x].fa;
		ans[now]=x;
		if(!t[x].fa)root=t[x].l;
		return;
	}
	find(t[x].l,now);
	swap(t[x].l,t[x].r);
}

int main()
{
	n=read();
	rep(i,1,n){
		int x=read();x++;
		if(x>=100)t[x-100].r=i+1,t[i+1].fa=x-100;
		else t[x].l=i+1,t[i+1].fa=x;
	}
	t[1].fa=0;
	dep(i,n+1,1)find(root,i);
	rep(i,1,n)
		printf("%d ",ans[i]-1);
	cout<<ans[n+1]-1;
	return 0;
}
		
本文可以转载,但必须附上原文链接,否则你会终生找不到妹子!!!欢迎关注我的CSDN: ahyjjr