选点

选点

 

分析:对于一颗树选出得点的权值的关系为:根节点 < 右子树 < 左子树。所以我们可以按照根节点、右子树、左子树进行 dfs 遍历,然后按照这个 dfs 序求 LIS 即为答案。用二分优化求LIS

AC_Code

 1 #include <iostream>
 2 #include <bits/stdc++.h>
 3 using namespace std;
 4 typedef long long ll;
 5 const int maxn = 1e5+10;
 6 const int inf=0x3f3f3f3f;
 7 #define rep(i,first,last) for(int i=first;i<=last;i++)
 8 #define dep(i,first,last) for(int i=first;i>=last;i--)
 9 int n,len;
10 int w[maxn],dp[maxn],e[maxn][2];
11 void dfs(int vertex){
12     dp[++len]=w[vertex];
13     if(e[vertex][1]) dfs(e[vertex][1]);
14     if(e[vertex][0]) dfs(e[vertex][0]);
15 }
16 int main()
17 {
18     scanf("%d",&n);
19     rep(i,1,n) scanf("%d",&w[i]);
20     rep(i,1,n) scanf("%d%d",&e[i][0],&e[i][1]);
21     len=0;
22     dfs(1);
23     dp[len=0]=-inf;
24     rep(i,1,n){
25         if( dp[len]<dp[i] ) dp[++len]=dp[i];
26         else{
27             int index=lower_bound(dp+1,dp+1+len,dp[i])-dp;
28             dp[index]=dp[i];
29         }
30     }
31     printf("%d\n",len);
32     return 0;
33 }

猜你喜欢

转载自www.cnblogs.com/wsy107316/p/12355763.html