이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#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({max(fm(j),fm(i)),min(i,j),max(i,j)});
}
}
int ans=0;
while(all.size()){
//cerr<<all.size()<<"\n";
/*
for(auto p:all){
cerr<<p[0]<<" "<<p[1]+1<<" "<<p[2]+1<<"\n";
}cerr<<"\n";
*/
auto p=*all.begin();
all.erase(p);
//cerr<<all.size()<<"\n";
v[p[2]].erase(p[1]);
v[p[1]].erase(p[2]);
if(fm(p[1])>fm(p[2])){
swap(p[2],p[1]);
}
ans+=fm(p[1])+fm(p[2]);
for(int i:v[p[1]]){
if(!all.empty()&&all.count({max(fm(p[1]),fm(i)),min(p[1],i),max(p[1],i)})){
//cerr<<all.size()<<"hmm1\n";
all.erase({max(fm(p[1]),fm(i)),min(p[1],i),max(p[1],i)});
//cerr<<all.size()<<"hmm2\n";
all.insert({max(fm(p[2]),fm(i)),min(p[1],i),max(p[1],i)});
}
}
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... |