(dfs序+lis)牛客练习赛39-B

https://ac.nowcoder.com/acm/contest/368/B

有一棵n个节点的二叉树,1为根节点,每个节点有一个值wi。现在要选出尽量多的点。
对于任意一棵子树,都要满足:
如果选了根节点的话,在这棵子树内选的其他的点都要比根节点的值大;
如果在左子树选了一个点,在右子树中选的其他点要比它小。

即为按照根节点-》右子树-》左子树的顺序选出最长上升子序列即可

#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
using namespace std;
typedef long long ll;

const int maxn = 1e5 + 4;
int rgt[maxn], lft[maxn];
int n, tot, dfsarr[maxn], lis[maxn], w[maxn], q[maxn];
void dfs(int pos) {
    dfsarr[++tot] = pos;
    if(rgt[pos]) dfs(rgt[pos]);
    if(lft[pos]) dfs(lft[pos]);
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin >> n;
    for(int i = 1; i <= n; i++) cin >> w[i];
    for(int i = 1; i <= n; i++) 
        cin >> lft[i] >> rgt[i];
    dfs(1);
    for(int i = 1; i <= n; i++) q[i] = w[dfsarr[i]];
    int ltot = 1;
    lis[1] = q[1];
    for(int i = 2; i <= n; i++) {
        if(q[i] > lis[ltot]) lis[++ltot] = q[i];
        else {
            int pos = lower_bound(lis + 1, lis + ltot + 1, q[i]) - lis;
            lis[pos] = q[i];
        }
    }
    cout << ltot << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值