[BZOJ1078]SCOI2008斜堆

仔细观察后发现最后插入的那个点满足下面两个性质
1.一定是极左节点,就是从根一直往左走可以走到的,因为X总是插入在左子树中。
2.一定没有右儿子,显然。
然后又发现,如果某一个点P满足这两个性质但它的祖先K中也有一个满足这两个性质,那么K一定后于P插入,要不然插入P的之前,K就是一个只有右子树的点,然而不可能有只有右子树的点。
所以我们找到满足这两个性质的深度最浅的点,然后把它记录到答案中,删除它,将它的祖先左右子树都交换(也就是还原回它插入之前的样子),然后继续找。
有一种特殊情况,就是P是叶节点而K恰好是P的父亲,为了字典序最小,我们先删除P。
代码:

type
  heap=^heapnode;
  heapnode=record
    t:longint;
    l,r,fa:heap;
  end;

var
  n,i,j,x,root:longint;
  h:array[0..500]of heap;
  ans:array[0..500]of longint;
  p:heap;
procedure ins(x,y:longint;b:boolean);
begin
  new(h[y]);
  h[y]^.t:=y;
  h[y]^.fa:=h[x];
  h[y]^.l:=nil;
  h[y]^.r:=nil;
  if b=false then h[x]^.l:=h[y]
  else h[x]^.r:=h[y];
end;
procedure del(x:heap);
var
  p,q:heap;
begin
  if x^.fa<>nil then x^.fa^.l:=x^.l;
  if x^.l<>nil then  x^.l^.fa:=x^.fa;
  if x^.t=root then root:=x^.l^.t;
  p:=x^.fa;
  x:=nil;
  while p<>nil do
  begin
    q:=p^.l;
    p^.l:=p^.r;
    p^.r:=q;
    p:=p^.fa;
  end;
end;
begin
  readln(n);
  new(h[0]);
  h[0]^.t:=0;
  h[0]^.l:=nil;
  h[0]^.r:=nil;
  h[0]^.fa:=nil;
  root:=0;
  for i:=1 to n do
  begin
    read(x);
    if x<100 then ins(x,i,false);
    if x>=100 then ins(x-100,i,true);
  end;
  for i:=n downto 1 do
  begin
    p:=h[root];
    while p<>nil do
    begin
      if p^.r=nil then break;
      p:=p^.l;
    end;
    if (p^.l<>nil)and(p^.l^.l=nil) then p:=p^.l;
    del(p);
    ans[i]:=p^.t;
  end;
  ans[0]:=root;
  for i:=0 to n do
    write(ans[i],' ');

end.  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值