#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
// using namespace chrono;
using namespace __gnu_pbds;
#define pb push_back
#define inf (1LL << 60)
#define all(x) (x).begin(), (x).end()
#define prDouble(x) cout << fixed << setprecision(10) << x
#define triplet pair<int, pair<int, int>>
#define fast_io \
ios_base::sync_with_stdio(false); \
cin.tie(NULL)
#define int long long
#define max3(a, b, c) max(max(a, b), c)
#define min3(a, b, c) min(min(a, b), c)
#define max4(a, b, c, d) max(a, max3(b, c, d))
#define min4(a, b, c, d) min(a, min3(b, c, d))
#define max5(a, b, c, d, e) max(max4(a, b, c, d), e)
#define min5(a, b, c, d, e) min(min4(a, b, c, d), e)
#define MAXN 100005
#define INF 1e18
#define mod 1000000007
#define mod2 998244353
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; // find_by_order, order_of_key
const int N = 1e5 + 10;
vector<int> adj[N];
int vis[N];
int res[N];
void dfs(int node, int par, vector<pair<int, int>> &temp, vector<int> &a)
{
vis[node] = 1;
temp.push_back({a[node], node});
for (int ch : adj[node])
{
if (ch != par)
{
dfs(ch, node, temp, a);
temp.pop_back();
}
}
// sort(temp.begin(),temp.end());
for (int i = 0; i < temp.size(); i++)
{
if (temp[i].first > a[node])
{
res[node] += 1;
}
}
res[node] = res[node] * a[node];
for (int i = 0; i < temp.size(); i++)
{
if (temp[i].first < a[node])
{
res[node] += temp[i].second;
}
}
return;
}
int32_t main()
{
fast_io;
int tc = 1;
// cin >> tc;
while (tc--)
{
int n;
cin >> n;
vector<int> a(n + 1);
for (int i = 1; i <= n; i++)
{
cin >> a[i];
}
for (int i = 1; i <= n - 1; i++)
{
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
vector<pair<int, int>> temp;
dfs(1, -1, temp, a);
for (int i = 1; i <= n; i++)
{
cout << res[i] << " ";
}
cout << endl;
}
return 0;
}
Is this optimal??