Source:POJ Monthly–2007.04.01, czh
题意:给出一棵可能不太完整的二叉树(缺的话只缺最下层)的节点权值,要求子节点的值不大于父亲节点的值,左儿子的值严格小于右儿子。问最少需要改变几个节点的值。
(树的高度不超过20)
想法:一开始看到这题是懵逼的,感觉这也能求太神奇了。
发现后序遍历之后,好像就是求一遍最长不递增子序列了。
只是要满足左儿子严格小于右儿子还需要思考,那么比如面对一个高度为2的完全二叉树,我们不妨把右儿子和根节点都减去1,这样就可以直接对这棵树的后序遍历求最长不递增子序列了。
求出来之后用原长减去这个序列的长度就好了。
这个类似LIS的有O(nlogn)的求法。
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int p[2100005];
int a[2100005];
int b[2100005];
int n,h,cnt=1;
void postorder(int now,int &d){
if ((now<<1)<=n) postorder(now<<1,d);
if ((now<<1|1)<=n) postorder(now<<1|1,++d);
a[cnt++]=p[now]-d;
}
int main(){
scanf("%d",&h);
n=0;
while(~scanf("%d",&p[++n]));
n--;
int d=0;
postorder(1,d);
cnt=0;
for(int i=1;i<=n;i++){
int *u=upper_bound(b,b+cnt,a[i]);
*u=a[i];
if (u-b==cnt) cnt++;
}
printf("%d\n",n-cnt);
return 0;
}
题目想通了感觉还是挺妙的。