获取最多食物-树形dp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int n;
vector<vector<int>> nodes;
vector<int> dp;
int dfs(int i)
{
if(dp[i] != INT_MIN) return dp[i];
if(nodes[i][0] == -1) return nodes[i][1];
dp[i] = max(nodes[i][1], nodes[i][1] + dfs(nodes[i][0]));
return dp[i];
}
int main()
{
cin >> n;
nodes = vector<vector<int>> (n, vector<int>(2));
for(int i = 0; i < n; i ++)
{
int id, pid, val;
cin >> id >> pid >> val;
nodes[id][0] = pid;
nodes[id][1] = val;
}
dp = vector<int> (n, INT_MIN);
for(int i = 0; i < n; i ++) dfs(i);
cout << *max_element(dp.begin(), dp.end()) << endl;
return 0;
}