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 ll long long
#define pii pair<int,int>
#define pb push_back
#define ff first
#define ss second
const int N=1e5+5;
ll ans;
int n,a[N];
int p[N],sz[N];
pii v[N];
bool compare(pii a1,pii a2){
return a[a1.ff]<a[a2.ff];
}
int find(int x){
if(x==p[x])return x;
return p[x]=find(p[x]);
}
void merge(int x,int y){
x=find(x);
y=find(y);
if(sz[x]<sz[y])swap(x,y);
ans+=a[x]+a[y];
p[y]=x;
sz[x]+=sz[y];
a[x]=max(a[x],a[y]);
}
int main(){
ios_base::sync_with_stdio(NULL);cin.tie(NULL);
cin>>n;
for(int i=1;i<=n;i++){
p[i]=i;
sz[i]=1;
cin>>a[i];
}
for(int i=0;i<n-1;i++){
int aa,bb;cin>>aa>>bb;
if(a[aa]<a[bb])swap(aa,bb);
v[i]={aa,bb};
}
sort(v,v+n-1,compare);
for(int i=0;i<n-1;i++){
int x=v[i].ff,y=v[i].ss;
merge(x,y);
}
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... |