Advertisement
Josif_tepe

Untitled

May 16th, 2023
649
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstring>
  4. using namespace std;
  5. const int maxn=5005;
  6. vector<int>graph[maxn];
  7. int arr[maxn];
  8. int parent[maxn];
  9. int dp[maxn];
  10. int dfs(int pos){
  11. if(dp[pos]!=-1){
  12.     return dp[pos];
  13. }
  14.    
  15. int r1=arr[pos];
  16. for(int i=0; i<graph[pos].size(); i++){
  17.     int sosed=graph[pos][i];
  18.     for(int j=0; j<graph[sosed].size(); j++){
  19.         int sosed_2=graph[sosed][j];
  20.         r1+=dfs(sosed_2);
  21.     }
  22. }
  23. int r2=0;
  24. for(int i=0; i<graph[pos].size(); i++){
  25.     r2+=dfs(graph[pos][i]);
  26. }
  27. return dp[pos]=max(r1, r2);
  28. }
  29.  
  30.  
  31.  
  32. int main()
  33. {
  34.     int n;
  35.     cin>>n>>arr[0];
  36.     int a, b;
  37.     for(int i=1; i<n; i++){
  38.     cin>>arr[i]>>b;
  39.     a=i;
  40.     parent[i]=b;
  41.     graph[b].push_back(i);
  42.     }
  43.     memset(dp, -1, sizeof dp);
  44.     cout<<dfs(0);
  45.     return 0;
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement