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

Description

斜堆(skew heap)是一种常用的数据结构。它也是二叉树,且满足与二叉堆相同的堆性质:每个非根结点的值
都比它父亲大。因此在整棵斜堆中,根的值最小。但斜堆不必是平衡的,每个结点的左右儿子的大小关系也没有任
何规定。在本题中,斜堆中各个元素的值均不相同。 在斜堆H中插入新元素X的过程是递归进行的:当H为空或者X
小于H的根结点时X变为新的树根,而原来的树根(如果有的话)变为X的左儿子。当X大于H的根结点时,H根结点的
两棵子树交换,而X(递归)插入到交换后的左子树中。 给出一棵斜堆,包含值为0~n的结点各一次。求一个结点
序列,使得该斜堆可以通过在空树中依次插入这些结点得到。如果答案不惟一,输出字典序最小的解。输入保证有
解。

Solution

可以发现每次插入的节点将会是从root一直向左遇到的第一个没有右子节点的节点(我没发现QAQ

http://www.cppblog.com/MatoNo1/archive/2013/03/03/192131.html

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
int n,root,ans[150];
struct Node
{
    int lch,rch,father;
    Node():lch(-1),rch(-1),father(-1){}
}heap[150];
int solve()
{
    int p=root;
    while(heap[p].rch!=-1)p=heap[p].lch;
    if(heap[p].lch!=-1&&heap[heap[p].lch].lch==-1&&heap[heap[p].lch].rch==-1)
    p=heap[p].lch;
    int t=p;
    if(p==root)
    {
        root=heap[p].lch;
        heap[heap[p].lch].father=-1;
        return p;
    }
    if(heap[p].lch!=-1)
    heap[heap[p].lch].father=heap[p].father,heap[heap[p].father].lch=heap[p].lch;
    else heap[heap[p].father].lch=-1;
    while(heap[t].father!=-1)
    {
        t=heap[t].father;
        swap(heap[t].lch,heap[t].rch);
    }
    return p;
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        int x;
        scanf("%d",&x);
        if(x>=100)heap[x-100].rch=i,heap[i].father=x-100;
        else heap[x].lch=i,heap[i].father=x;
    }
    root=0;
    for(int i=n;i>=0;i--)
    ans[i]=solve();
    for(int i=0;i<=n;i++)
    printf("%d ",ans[i]);
    return 0;
} 

 

posted @ 2017-05-20 19:59  Zars19  阅读(187)  评论(0编辑  收藏  举报