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;
const int mxx=1e5+10;
typedef long long ll;
int inf=1e9+10;
const int mod=1e9+7;
int a[mxx];
ll ans=0;
pair<int,int>edge[mxx];
int n;int par[mxx];
int mx[mxx];
int siz[mxx];
vector<int>adj[mxx];
void init(){
for(int i=0;i<n;i++){
par[i]=i;
mx[i]=a[i];
siz[i]=1;
}
}
int fin(int node){
if(par[node]!=node){
return par[node]=fin(par[node]);
}else{
return node;
}
}
void unit(int a,int b){
int aa=fin(a);
int bb=fin(b);
if(siz[a]>siz[b]){
swap(a,b);
}
if(aa==bb){
return;
}
par[aa]=bb;
//ans+=(mx[aa]+mx[bb]);
mx[bb]=max(mx[bb],mx[aa]);
return;
}
int active[mxx];
int main(){
cin>>n;
pair<int,int>v[n];
for(int i=0;i<n;i++){
cin>>a[i];
v[i]={a[i],i};
}
for(int i=0;i<n-1;i++){
int x,y;
cin>>x>>y;
x--;y--;
adj[x].push_back(y);
adj[y].push_back(x);
edge[i]={x,y};
}
init();
sort(v,v+n);
vector<pair<int,int>>x;
for(int i=0;i<n;i++){
int me=v[i].second;
active[me]=1;
for(auto it:adj[me]){
if(active[it]){
// cout<<v[i].first<<" "<<mx[it]<<" ";
ans+=v[i].first;
ans+=mx[fin(it)];
}
}
for(auto it:adj[me]){
if(active[it]){
unit(it,me);
}
}
}
///cout<<endl;
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... |