Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <bits/stdc++.h>
- using namespace std;
- const int maxn = 3e5 + 10;
- vector<int> graph[maxn];
- int rating[maxn];
- int parent[maxn];
- int dp[maxn];
- int dfs(int node) {
- if(dp[node] != -1) {
- return dp[node];
- }
- int taken = rating[node];
- for(int i = 0; i < (int) graph[node].size(); i++) {
- int neighbour = graph[node][i];
- for(int j = 0; j < (int) graph[neighbour].size(); j++) {
- int neighbour_of_neighbour = graph[neighbour][j];
- taken += dfs(neighbour_of_neighbour);
- }
- }
- int not_taken = 0;
- for(int i = 0; i < (int) graph[node].size(); i++) {
- int neighbour = graph[node][i];
- not_taken += dfs(neighbour);
- }
- return dp[node] = max(taken, not_taken);
- }
- int main() {
- ios_base::sync_with_stdio(false);
- memset(dp, -1, sizeof dp);
- int n;
- cin >> n;
- cin >> rating[0];
- for(int i = 1; i < n; i++) {
- int p;
- cin >> rating[i] >> p;
- parent[i] = p;
- graph[p].push_back(i);
- }
- cout << dfs(0) << endl;
- return 0;
- }
- /*
- 7
- 1 2
- 1 3
- 2 4
- 2 5
- 3 6
- 3 7
- **/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement