이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
//author: Ahmet Alp Orakci
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
struct DSU {
int n;
vector <int> par;
vector <int> vals;
DSU(int n) : n(n) {
par.resize(n +5);
vals.resize(n +5);
iota(par.begin(), par.end(), 0ll);
}
inline void build(vector <int> &vec) {
for(int i = 1; i <= n; i++) {
vals[i] = vec[i];
}
}
inline int get(int a) {
return par[a] = (par[a] == a ? a : get(par[a]));
}
inline bool same(int a, int b) {
return get(a) == get(b);
}
inline bool unite(int a, int b) {
if(same(a, b))
return false;
par[a] = b;
vals[b] = max(vals[b], vals[a]);
return true;
}
inline int val(int a) {
return vals[get(a)];
}
};
#define ONLINE_JUDGE
void solve() {
int n;
cin >> n;
vector <int> vec(n +1);
for(int i = 1; i <= n; i++)
cin >> vec[i];
vector <int> adj[n +1];
for(int i = 1; i <= n -1; i++) {
int u, v;
cin >> u >> v;
adj[u].emplace_back(v);
adj[v].emplace_back(u);
}
DSU dsu(n);
dsu.build(vec);
vector <int> inds(n +1);
iota(inds.begin(), inds.end(), 0ll);
sort(inds.begin(), inds.end(), [&](int a, int b) -> bool {
return vec[a] < vec[b];
});
vector <bool> activated(n +5, false);
i64 res = 0;
for(int i = 1; i <= n; i++) {
int node = inds[i];
activated[node] = true;
int mx = dsu.val(node);
for(int &child : adj[node]) {
if(activated[child]) {
res += 0LL + mx + dsu.val(child);
dsu.unite(child, node);
}
}
}
cout << res << "\n";
return;
}
signed main() {
#ifndef ONLINE_JUDGE
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int t = 1; //cin >> t;
for(int i = 1; i <= t; i++) {
solve();
}
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... |