Pak Chanek has n blank heart-shaped cards. Card 11 is attached directly to the wall while each of the other cards is hanging onto exactly one other card by a piece of string. Specifically, card i (i>1) is hanging onto card pi (pi<i).
In the very beginning, Pak Chanek must write one integer number on each card. He does this by choosing any permutation a of [1,2,…,n]. Then, the number written on card i is ai.
After that, Pak Chanek must do the following operation n times while maintaining a sequence s (which is initially empty):
- Choose a card x such that no other cards are hanging onto it.
- Append the number written on card x to the end of s.
- If x≠1 and the number on card px is larger than the number on card x, replace the number on card px with the number on card x.
- Remove card x.
After that, Pak Chanek will have a sequence s with n elements. What is the maximum length of the longest non-decreasing subsequence†† of s at the end if Pak Chanek does all the steps optimally?
†† A sequence b is a subsequence of a sequence c if b can be obtained from c by deletion of several (possibly, zero or all) elements. For example, [3,1] is a subsequence of [3,2,1], [4,3,1] and [3,1], but not [1,3,3,7] and [3,10,4].
Input
The first line contains a single integer n (2≤n≤105) — the number of heart-shaped cards.
The second line contains n−1 integers p2,p3,…,pn (1≤pi<i) describing which card that each card hangs onto.
Output
Print a single integer — the maximum length of the longest non-decreasing subsequence of s at the end if Pak Chanek does all the steps optimally.
Examples
input
Copy
6
1 2 1 4 2
output
Copy
4
input
Copy
2
1
output
Copy
2
题意: 给定一个树,我们的目标是构造树的点权。每次操作可以选择一个叶子节点,并且摘掉这个叶子节点并且获得叶子节点的权值。每次摘叶子的时候,如果你摘的叶子的权值比他的父节点小,那么父节点的权值就会变成这个叶子的权值,一直进行到树被摘完。最终我们会获得摘叶子的序列,起价值是该序列的最长非下降子序列。请合理的构造树上的权值,最大化操作后的价值。
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
#define all(x) (x).begin(),(x).end()
#define X first
#define Y second
#define sep ' '
#define endl '\n'
#define SZ(x) ll(x.size())
const ll MAXN = 1e6 + 10;
const ll LOG = 22;
const ll INF = 8e18;
const ll MOD = 1e9 + 7; //998244353; //1e9 + 9;
int pow_mod(int a1, int n1, int m1)
{
if(n1 == 0) return 1;
int x = pow_mod(a1, n1/2, m1);
long long ans = (long long)x * x % m1;
if(n1 % 2 == 1) ans = ans *a1 % m1;
return (int)ans;
}
int n , ans , P[MAXN] , dp[MAXN] , mx[MAXN];
vector<int> adj[MAXN];
int main() {
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin >> n;
for(int i = 2 ; i <= n ; i++){
cin >> P[i];
adj[P[i]].push_back(i);
}
for(int i = n ; i >= 1 ; i--){
for(int j : adj[i]){
dp[i] += dp[j];
mx[i] = max(mx[i] , mx[j]);
}
mx[i]++;
dp[i] = max(dp[i] , mx[i]);
}
cout << dp[1] << endl;
return 0;
}