题解 爆零
原题,dfs即可
Code:
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
#define N 1000010
#define ll long long
#define reg register int
#define fir first
#define sec second
#define make make_pair
#define pb push_back
//#define int long long
char buf[1<<21], *p1=buf, *p2=buf;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf, 1, 1<<21, stdin)), p1==p2?EOF:*p1++)
inline int read() {
int ans=0, f=1; char c=getchar();
while (!isdigit(c)) {if (c=='-') f=-f; c=getchar();}
while (isdigit(c)) {ans=(ans<<3)+(ans<<1)+(c^48); c=getchar();}
return ans*f;
}
int n;
int head[N], size;
struct edge{int to, next;}e[N<<1];
inline void add(int s, int t) {e[++size].to=t; e[size].next=head[s]; head[s]=size;}
namespace task1{
int dep[N], ans, dis, mdep[N];
vector< pair<int, int> > son[N];
void dfs1(int u) {
mdep[u]=dep[u];
for (int i=head[u],v; ~i; i=e[i].next) {
v = e[i].to;
dep[v]=dep[u]+1;
dfs1(v);
mdep[u]=max(mdep[u], mdep[v]);
son[u].pb(make(mdep[v], v));
}
sort(son[u].begin(), son[u].end());
// cout<<"son: "<<u<<' '; for (auto it:son[u]) cout<<it.fir<<','<<it.sec<<' '; cout<<endl;
}
void dfs2(int u) {
ans+=min(dis, dep[u]-1);
dis=0;
for (auto v:son[u]) {
++dis;
dfs2(v.sec);
++dis;
}
}
void solve() {
dep[1]=1; dfs1(1);
dfs2(1);
printf("%d\n", ans);
exit(0);
}
}
signed main()
{
freopen("a.in", "r", stdin);
freopen("a.out", "w", stdout);
memset(head, -1, sizeof(head));
n=read();
for (int i=2; i<=n; ++i) add(read(), i);
task1::solve();
return 0;
}