This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5;
int n, ds[N + 5], M[N + 5];
vector<int> g[N + 5];
int Get(int pos)
{
if (pos == ds[pos])
return pos;
return ds[pos] = Get(ds[pos]);
}
void Join(int u, int v)
{
u = Get(u), v = Get(v);
M[u] = max(M[u], M[v]);
ds[v] = u;
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
// freopen ("file.inp","r",stdin);
// freopen ("file.out","w",stdout);
cin >> n;
vector<pair<int, int>> v;
for (int i = 1; i <= n; i++)
{
int a;
cin >> a;
M[i] = a;
ds[i] = i;
v.push_back({a, i});
}
for (int i = 1; i < n; i++)
{
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
long long ans = 0;
sort(v.begin(), v.end());
for (int i = 0; i < n; i++)
{
int pos = v[i].second;
for (int j : g[pos])
if (Get(pos) != Get(j) && M[Get(pos)] >= M[(Get(j))])
{
ans += M[Get(j)] + M[Get(pos)];
Join(pos, j);
}
}
cout << ans;
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |