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;
struct DSU{
vector<int> par,sz,mx_val;
DSU(int n, int t[]): par(n+1), sz(n+1), mx_val(n+1){
for(int i = 1; i <= n; i++){
par[i] = i;
sz[i] = 1;
mx_val[i] = t[i];
}
return;
}
int asc(int x){
return x == par[x] ? x : par[x] = asc(par[x]);
}
bool join(int u, int v){
u = asc(u), v = asc(v);
if(u == v) return false;
if(sz[u] < sz[v]) swap(u, v);
par[v] = u;
sz[u] += sz[v];
mx_val[u] = max(mx_val[u], mx_val[v]);
return true;
}
int weight(int u){
return mx_val[asc(u)];
}
};
using ll = long long;
const int N = 1e5+5;
int n, t[N], deg[N];
priority_queue<pair<int,int>> pq;
vector<int> adj[N];
vector<pair<int,int>> Edge;
void solve()
{
cin >> n;
for(int i = 1; i <= n; i++){
cin >> t[i];
pq.push(make_pair(t[i], i));
}
for(int i = 1; i < n; i++){
int u,v; cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
++deg[u], ++deg[v];
}
while(!pq.empty()){
pair<int,int> e = pq.top(); pq.pop();
int x = e.second, w = e.first;
if(!deg[x]) continue;
for(int v : adj[x]){
if(deg[v]){
Edge.push_back(make_pair(v, x));
--deg[v], --deg[x];
}
}
}
reverse(Edge.begin(), Edge.end());
DSU dsu(n, t);
ll answer = 0;
for(pair<int,int>& e : Edge){
int u = e.first, v = e.second;
answer = answer + 1ll * dsu.weight(u) + 1ll * dsu.weight(v);
dsu.join(u, v);
}
cout << answer <<"\n";
}
int32_t main(){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
#define name "InvMOD"
if(fopen(name".INP", "r")){
freopen(name".INP", "r", stdin);
freopen(name".OUT", "w", stdout);
}
solve();
return 0;
}
Compilation message (stderr)
sjekira.cpp: In function 'void solve()':
sjekira.cpp:63:27: warning: unused variable 'w' [-Wunused-variable]
63 | int x = e.second, w = e.first;
| ^
sjekira.cpp: In function 'int32_t main()':
sjekira.cpp:93:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
93 | freopen(name".INP", "r", stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
sjekira.cpp:94:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
94 | freopen(name".OUT", "w", stdout);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
# | 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... |