跳到正文

题解

题解 P2475 【[SCOI2008]斜堆】

逍遥天堂约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
题目
P2475

版本

  1. v1当前

//转自CSDN博客 侵权立删 提供一种递归思路

分类讨论后得出结论,最后插入的一定是深度最小的那个满足条件的点。即x的左子树是叶子。

为了满足字典序最小,我们选择叶子作为最后的插入点。

我们由此发现了两个神奇的性质

1.一个结点有右子树则必有左子树(右子树不可能单独存在)

2.最后插入的那个点一定是一直沿着左边往下走,并且没有右子树。

C++
#include<bits/stdc++.h>
using namespace std;
int n,root,ans[105];
struct tree
{
	int l,r,fa;
}a[105];
void Get(int x,int now)
{
	if((!a[x].r&&!a[x].l)||(!a[x].r&&a[x].l&&(a[a[x].l].l)))
	{
		a[a[x].fa].l=a[x].l;
		if(a[x].l)
			a[a[x].l].fa=a[x].fa;
		ans[now]=x;
		if(!a[x].fa)
			root=a[x].l;
		return;
	}
	Get(a[x].l,now);
	swap(a[x].l,a[x].r);
}
int main()
{
	root=1;
    scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		int x;
		scanf("%d",&x);
		x++;
		if(x<100)
			a[x].l=i+1,a[i+1].fa=x;
		else
		{
			x-=100;
			a[x].r=i+1,a[i+1].fa=x;
		}
	}
	a[1].fa=0;
	for(int i=n+1;i;i--)
		Get(root,i);
	for(int i=1;i<=n;i++)
		printf("%d ",ans[i]-1);
	cout<<ans[n+1]-1;
	return 0;
}
原文