dfs+LIS(O(nlogn))

链接:https://ac.nowcoder.com/acm/contest/368/B
来源:牛客网
 

选点

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld

题目描述

有一棵n个节点的二叉树,1为根节点,每个节点有一个值wi。现在要选出尽量多的点。

对于任意一棵子树,都要满足:

如果选了根节点的话,在这棵子树内选的其他的点都要比根节点的值

如果在左子树选了一个点,在右子树中选的其他点要比它

输入描述:

 

第一行一个整数n。

第二行n个整数wi,表示每个点的权值。

接下来n行,每行两个整数a,b。第i+2行表示第i个节点的左右儿子节点。没有为0。

n,a,b≤105,−2×109≤wi≤2×109n,a,b≤105,−2×109≤wi≤2×109

输出描述:

一行一个整数表示答案。

示例1

输入

复制

5
1 5 4 2 3
3 2
4 5
0 0
0 0
0 0 

输出

复制

3

解题思路:

就是将树按照先根,再右子树,再左子树遍历。然后求最大上升子序列,O(n^2)的LIS过不去。。。

#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
const int N = 100005;
int w[N], ls[N], rs[N], q[N], f[N], tot;
void dfs(int u) {
	if (!u) return ;
	q[++tot] = u;
	dfs(rs[u]);
	dfs(ls[u]);
}
int main() {
	int n;
	scanf("%d", &n);
	for (int i=1; i<=n; ++i) scanf("%d", &w[i]);
	for (int i=1; i<=n; ++i) scanf("%d%d", &ls[i], &rs[i]);
	dfs(1);
	f[1]=q[1];
	int len=1;
	for (int i=2; i<=n; ++i) {
		if(q[i]>f[len]) f[++len]=q[i];
		else{
			int pos=lower_bound(f+1,f+len+1,q[i])-f;
			f[pos]=q[i];
		}
	}
	cout << len;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41755258/article/details/86777483