This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#ifndef Local
#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
#endif
#include <bits/stdc++.h>
#define int long long
#define pb push_back
#define lim 100005
using namespace std;
const int mod=1000000007ll;
int parent[lim];
int maxi[lim];
int find(int i){
if(parent[i]==i){
return i;
}
return parent[i]=find(parent[i]);
}
int fm(int i){
return maxi[find(i)];
}
void unite(int i,int j){
int x=find(i),y=find(j);
if(x!=y){
maxi[y]=maxi[x]=max(maxi[x],maxi[y]);
parent[y]=x;
}
}
unordered_set<int>v[lim];
void solve(){
int n;
cin>>n;
int h[n];
for(int i=0;i<n;i++){
cin>>h[i];
}
for(int i=0;i<n-1;i++){
int x,y;
cin>>x>>y;
x--,y--;
v[x].insert(y);
v[y].insert(x);
}
for(int i=0;i<n;i++){
parent[i]=i;
maxi[i]=h[i];
}
set<array<int,3>>all;
for(int i=0;i<n;i++){
for(int j:v[i]){
all.insert({fm(i)+fm(j),min(i,j),max(i,j)});
}
}
int ans=0;
while(all.size()){
//cerr<<all.size()<<"\n";
auto p=*all.begin();
all.erase(p);
//cerr<<all.size()<<"\n";
v[p[0]].erase(p[1]);
v[p[1]].erase(p[0]);
if(fm(p[1])>fm(p[2])){
swap(p[2],p[1]);
}
ans+=p[0];
for(int i:v[p[1]]){
if(all.count({fm(p[1])+fm(i),min(p[1],i),max(p[1],i)})){
//cerr<<all.size()<<"hmm1\n";
all.erase({fm(p[1])+fm(i),min(p[1],i),max(p[1],i)});
//cerr<<all.size()<<"hmm2\n";
all.insert({fm(p[2])+fm(i),min(p[1],i),max(p[1],i)});
}
}
/*
for(auto p:all){
cerr<<p[0]<<" "<<p[1]<<" "<<p[2]<<"\n";
}
*/
unite(p[1],p[2]);
}
cout<<ans<<"\n";
}
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
#ifdef Local
freopen("in","r",stdin);
freopen("out","w",stdout);
#endif
int t=1;
//cin>>t;
while (t--)
{
solve();
}
}
# | 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... |