其实就是简单的树形dp;
假设v1,v2,v3..vs是u的儿子,那么将dp[vi]从大到小排序;
dp[u] = max(dp[v_i] + i];
Code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<math.h>
using namespace std;
#define sf scanf
#define pf printf
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define ll long long
#define CLR(a) memset((a),0,sizeof((a)))
#define bug(x) cerr << "line: " << __LINE__ << ' ' << #x << " =" << (x) << endl;
#define nMax 100010
vector<int> to[nMax];
int n;
int s;
int dp[nMax],vis[nMax];
int inline min(int x,int y) { return x < y ? x : y; }
int inline max(int x,int y) { return x > y ? x : y; }
#define pb push_back
void dfs(int u) {
vis[u] = 1;
int num = 0;
vector<int> tmp;tmp.clear();
for(int i=0,v;i<to[u].size();i++) if(!vis[v = to[u][i]]) {
num ++;
dfs(v);
tmp.pb(dp[v]);
}
if(num==0) dp[u]=0;
else {
dp[u] = 0;
sort(tmp.begin(),tmp.end(),greater<int>());
for(int i=1;i<=num;i++) {
dp[u] = max(dp[u],tmp[i-1]+i);
}
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
while(~sf("%d",&n)) {
for(int i=1;i<=n;i++) to[i].clear(),vis[i]=0;
for(int u,i=1;i<=n;i++) {
while(1) {
sf("%d",&u);
if(u == 0) break;
to[i].pb(u);
to[u].pb(i);
}
}
int u;
sf("%d",&u);
dfs(u);
pf("%d\n",dp[u]);
}
return 0;
}