(dfs+LIS)牛客练习赛39-选点

链接: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

注意:dfs遍历时,要从右子树向左子树进行遍历

#include<set>
#include<map>
#include<list>
#include<queue>
#include<stack>
#include<math.h>
#include<vector>
#include<bitset>
#include<iomanip>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define eps (1e-8)
#define MAX 0x3f3f3f3f
#define u_max 1844674407370955161
#define l_max 9223372036854775807
#define i_max 2147483647
#define re register
#define pushup() tree[rt]=max(tree[rt<<1],tree[rt<<1|1])
#define nth(k,n) nth_element(a,a+k,a+n);  // 将 第K大的放在k位
#define ko() for(int i=2;i<=n;i++) s=(s+k)%i // 约瑟夫
#define ok() v.erase(unique(v.begin(),v.end()),v.end()) // 排序,离散化
using namespace std;

inline int read(){
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' & c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}

typedef long long ll;
const double pi = atan(1.)*4.;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3fLL;
const int M=63;
const int N=1e5+5;
map<int,int>mapp;
vector<int>v[N];
int a[N],p=0;
void dfs(int x){
    int h=upper_bound(a,a+p,mapp[x])-a;
    if(h==p)
        a[p++]=mapp[x];
    else
        a[h]=mapp[x];
    for(int i=0;i<v[x].size();i++)
        dfs(v[x][i]);
    return ;
}
int main(){
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        int x;
        scanf("%d",&x);
        mapp[i]=x;
    }
    for(int i=1;i<=n;i++){
        int x,y;
        scanf("%d %d",&x,&y);
        if(y)
           v[i].push_back(y);
        if(x)
           v[i].push_back(x);
    }
    dfs(1);
    printf("%d\n",p);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/black_horse2018/article/details/87262004