Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- typedef long long ll;
- const int maxn = 1e5 + 10;
- int n;
- int experience[maxn];
- vector<int> graph[maxn];
- ll dp[maxn][3];
- void dfs(int node, int parent) {
- ll sum = 0;
- for(int neighbour : graph[node]) {
- if(neighbour != parent) {
- dfs(neighbour, node);
- sum += dp[neighbour][0];
- }
- }
- dp[node][1] = sum + experience[node];
- dp[node][2] = sum - experience[node];
- for(int neighbour : graph[node]) {
- if(neighbour != parent) {
- dp[node][1] = max(dp[node][1], sum - dp[neighbour][0] + dp[neighbour][1]);
- dp[node][2] = max(dp[node][2], sum - dp[neighbour][0] + dp[neighbour][2]);
- }
- }
- dp[node][0] = max(dp[node][1] - experience[node], dp[node][2] + experience[node]);
- }
- int main()
- {
- ios_base::sync_with_stdio(false);
- cin >> n;
- for(int i = 0; i < n; i++) {
- cin >> experience[i];
- }
- for(int i = 1; i < n; i++) {
- int a, b;
- cin >> a >> b;
- a--; b--;
- graph[a].push_back(b);
- graph[b].push_back(a);
- }
- dfs(0, -1);
- cout << dp[0][0] << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement