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;
#define lli long long int
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define pii pair <int, int>
#define X first
#define Y second
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define info() cout << __PRETTY_FUNCTION__ << ": " << __LINE__ << endl
void abc() {cout << endl;}
template <typename T, typename ...U> void abc(T a, U ...b) {
cout << a << ' ', abc(b...);
}
template <typename T> void printv(T l, T r) {
while (l != r) cout << *l << " \n"[++l == r];
}
template <typename A, typename B> istream& operator >> (istream& o, pair<A, B> &a) {
return o >> a.X >> a.Y;
}
template <typename A, typename B> ostream& operator << (ostream& o, pair<A, B> a) {
return o << '(' << a.X << ", " << a.Y << ')';
}
template <typename T> ostream& operator << (ostream& o, vector<T> a) {
bool is = false;
if (a.empty) o << '{';
for (T i : a) {o << (is ? ' ' : '{'), is = true, o << i;}
return o << '}';
}
template <typename T> struct vv : vector <vector <T>> {
vv(int n, int m, T v) : vector <vector <T>> (n, vector <T>(m, v)) {}
vv() {}
};
template <typename T> struct vvv : vector <vv <T>> {
vvv(int n, int m, int k, T v) : vector <vv <T>> (n, vv <T>(m, k, v)) {}
vvv() {}
};
#ifdef Doludu
#define test(args...) info(), abc("[" + string(#args) + "]", args)
#define owo freopen("input.txt", "r", stdin), freopen("output.txt", "w", stdout)
#else
#define test(args...) void(0)
#define owo ios::sync_with_stdio(false); cin.tie(0)
#endif
const int mod = 1e9 + 7, N = 200001, logN = 20, K = 80000;
vector <int> adj[N];
vector <int> dsu;
int Find(int x) {
if (dsu[x] == x) return x;
return dsu[x] = Find(dsu[x]);
}
int main () {
owo;
int n;
cin >> n;
vector <int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
for (int i = 0, u, v; i < n - 1; ++i) {
cin >> u >> v, --u, --v;
adj[u].pb(v);
adj[v].pb(u);
}
vector <int> p(n);
iota(all(p), 0);
sort(all(p), [&](int i, int j) {
return a[i] > a[j];
});
dsu.resize(n);
iota(all(dsu), 0);
vector <pii> tmp;
lli ans = 0;
for (int i : p) {
for (int j : adj[i]) if (a[i] > a[j]) {
tmp.eb(i, j);
}
}
reverse(all(tmp));
for (pii i : tmp) {
ans += a[Find(i.X)] + a[Find(i.Y)];
i.X = Find(i.X), i.Y = Find(i.Y);
if (a[i.X] > a[i.Y]) swap(i.X, i.Y);
dsu[i.X] = i.Y;
}
cout << ans << endl;
}
# | 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... |