原题链接:https://pintia.cn/problem-sets/994805046380707840/exam/problems/1518582482059845632?type=7&page=1
树 + 递推
主要是理解树的一些性质之后直接用递推就能够实现
#include <bits/stdc++.h>
#define ll long long
const ll N = 1e6;
ll op[N];
ll res = 0;//s送完所有快递的最长时间
ll df = 0;//深度
ll dp[N];//这个点是否遍历
ll check(ll aa){//检查要这个快递的时间
if(op[aa] == -1 || dp[aa] > 0) return dp[aa];
df ++;
dp[aa] = check(op[aa]) + 1;
return dp[aa];
}
void solve(){
ll n,m;
std::cin >> n >> m;
for(ll i = 1; i <= n; i ++){
std::cin >> op[i];
}
for(ll i = 1; i <= m; i ++){
ll a;
std::cin >> a;
ll re = check(a);
res = std::max(res,re);
std::cout << df * 2 - res;
if(i != m) std::cout << "\n";
}
}
int main(){
ll t = 1;
while(t --)
solve();
return 0;
}