Official

E - Family and Insurance Editorial by en_translator


Let \(\mathrm{dp}_i\) be “how many next generations of person \(i\) are covered.” If person \(i\) themself is the last generation, \(\mathrm{dp}_i = 0\), and if person \(i\) is not covered, \(\mathrm{dp}_i =-1\).
Defining \(m_i\) by the maximum \(y_j\) for \(j\) such that \(x_j=i\) (or \(-1\) if no such \(j\) exists), we have that \(\mathrm{dp}_i = \max(m_i, \mathrm{dp}_{p_i}-1 )\). (Only the former is valid for \(i=1\) because \(p_i\) is undefined.) Fill them in ascending order of \(i\), and count the number of \(i\) such that \(\mathrm{dp}_i \geq 0\), to find the correct answer.

Sample code (C++)

#include <bits/stdc++.h>
using namespace std;
	
int main() {
    
	int N,M;
	cin>>N>>M;
	
	vector<int> p(N);
	
	for(int i=1;i<N;i++){
		cin>>p[i];
		p[i]--;
	}
	
	vector<int> dp(N,-1);
	
	for(int i=0;i<M;i++){
		int x,y;
		cin>>x>>y;
		x--;
		dp[x] = max(dp[x],y);
	}
	
	for(int i=1;i<N;i++){
		dp[i] = max(dp[i],dp[p[i]]-1);
	}
	
	int ans = 0;
	for(int i=0;i<N;i++){
		if(dp[i]>=0)ans++;
	}
	
	cout<<ans<<endl;
	
	return 0;
}

posted:
last update: