Code : Max Sum on Downward Path
#include <bits/stdc++.h>
using namespace std;
class Tree {
public:
int n, timer;
vector<vector<int>> adj;
vector<int> tin, tout;
vector<long long> a, event;
Tree(int n) {
this->n = n;
adj.resize(n);
tin.resize(n);
tout.resize(n);
a.resize(n);
event.resize(2 * n + 1);
timer = 0;
}
public:
void dfs(int src, int par) {
tin[src] = ++timer;
event[tin[src]] = a[src];
for (auto child : adj[src]) {
if (child != par) {
dfs(child, src);
}
}
tout[src] = ++timer;
event[tout[src]] = -a[src];
}
};
void solve() {
int n;
cin >> n;
Tree t(n);
for (int i = 0; i < n; i++) {
cin >> t.a[i];
}
for (int i = 0; i < n - 1; i++) {
int x, y;
cin >> x >> y;
x--;
y--;
t.adj[x].push_back(y);
t.adj[y].push_back(x);
}
t.dfs(0, -1);
for (int i = 0; i < n; i++) {
long long mx = t.event[t.tin[i]], prefix_sum = 0;
// Make sure to exclude tout[i] to avoid empty path.
for (int x = t.tin[i]; x < t.tout[i]; x++) {
prefix_sum += t.event[x];
mx = max(mx, prefix_sum);
}
cout << mx << " ";
}
cout << endl;
}
int main() {
int t;
cin >> t;
for (int zz = 0; zz < t; zz++) {
solve();
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
class Tree {
public:
int n, timer;
vector<vector<int>> adj;
vector<long long> a, dp;
Tree(int n) {
this->n = n;
adj.resize(n);
a.resize(n);
dp.resize(n);
timer = 0;
}
public:
void dfs(int src, int par) {
dp[src] = a[src];
for (auto child : adj[src]) {
if (child != par) {
dfs(child, src);
dp[src] = max(dp[src], a[src] + dp[child]);
}
}
}
};
void solve() {
int n;
cin >> n;
Tree t(n);
for (int i = 0; i < n; i++) {
cin >> t.a[i];
}
for (int i = 0; i < n - 1; i++) {
int x, y;
cin >> x >> y;
x--;
y--;
t.adj[x].push_back(y);
t.adj[y].push_back(x);
}
t.dfs(0, -1);
for (int i = 0; i < n; i++) {
cout << t.dp[i] << " ";
}
cout << endl;
}
int main() {
int t;
cin >> t;
for (int zz = 0; zz < t; zz++) {
solve();
}
return 0;
}