#include <bits/stdc++.h> using namespace std; #define ll long long #define re register #define fi first #define se second #define mp make_pair #define pb push_back #define P pair<int,int> const int N=1e4; const int mod=1e9+7; void read(int &a) { a=0; int d=1; char ch; while(ch=getchar(),ch>‘9‘||ch<‘0‘) if(ch==‘-‘) d=-1; a=ch-‘0‘; while(ch=getchar(),ch>=‘0‘&&ch<=‘9‘) a=a*10+ch-‘0‘; a*=d; } void write(int x) { if(x<0) putchar(45),x=-x; if(x>9) write(x/10); putchar(x%10+‘0‘); } int dep[1005],f[1005],d[1005],a[1005]; bool cmp(int x,int y) { return dep[x]>dep[y]; } int main() { int n; read(n); d[0]=d[1]=N; a[1]=1; for(re int i=2;i<=n;i++) { read(f[i]); d[i]=N; dep[i]=dep[f[i]]+1; a[i]=i; } sort(a+1,a+n+1,cmp); int ans=0; for(re int i=1;i<=n;i++) { int u=a[i]; int v=f[u]; int w=f[v]; d[u]=min(d[u],min(d[v]+1,d[w]+2)); if(d[u]>2) { d[w]=0;///在最底层上两个建,贪心。 ans++; d[f[w]]=min(d[f[w]],1);///更新在这个消防站的上两个点 d[f[f[w]]]=min(d[f[f[w]]],2); } } write(ans); return 0; }
原文:https://www.cnblogs.com/acm1ruoji/p/10693544.html