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;
using ll = long long;
const int maxn = 1e5 + 5;
ll ans = 0;
int par[maxn], sz[maxn], mx[maxn];
int find(int u) {
if(u == par[u]) return u;
return par[u] = find(par[u]);
}
void uni(int a, int b) {
a = find(a); b = find(b);
ans += mx[a] + mx[b];
if(sz[a] < sz[b]) swap(a, b);
sz[a] += sz[b];
mx[a] = max(mx[a], mx[b]);
par[b] = a;
}
int main() {
int n;
cin >> n;
vector<int> v(n+1);
for(int i=1; i<=n; i++) cin >> v[i];
for(int i=1; i<=n; i++) par[i] = i, sz[i] = 1, mx[i] = v[i];
vector<array<int, 3> > edges;
for(int i=0; i<n-1; i++) {
int a, b;
cin >> a >> b;
edges.push_back({ max(v[a], v[b]), a, b });
}
sort(v.begin(), v.end());
for(auto &[_, a, b] : edges) uni(a, b);
cout << ans << '\n';
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... |