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 int long long
#define ff first
#define ss second
#define pb push_back
const int N=3e5+5;
int par[N],c[N],sbtr[N],mx[N];
vector<int>v[N];
int ans=0;
bool vis[N];
int find(int x){
if(x==par[x])return x;
return par[x]=find(par[x]);
}
void merge(int x, int y){
int px=find(x),py=find(y);
if(sbtr[px]<sbtr[py]){
swap(py,px);
}
ans+=mx[px]+mx[py];
sbtr[px]+=sbtr[py];
mx[px]=max(mx[px],mx[py]);
par[py]=px;
}
bool cmp(const pair<int,int> & a, const pair<int,int> & b) {
int x = max(c[a.first], c[a.second]);
int y = max(c[b.first], c[b.second]);
return x<y;
}
signed main(){
int n;
cin>>n;
vector<pair<int,int>>vc;
for(int i=1;i<=n;i++){
cin>>c[i];
par[i]=i;
sbtr[i]=1;
mx[i]=c[i];
}
for(int i=1;i<n;i++){
int a,b;
cin>>a>>b;
v[a].pb(b);
v[b].pb(a);
vc.pb({a,b});
}
sort(vc.begin(),vc.end(),cmp);
for(auto p:vc){
int a=p.ss;
int b=p.ff;
merge(a,b);
}
cout<<ans;
}
# | 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... |