이 제출은 이전 버전의 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;
}
}
vector<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].pb(y);
v[y].pb(x);
}
for(int i=0;i<n;i++){
parent[i]=i;
maxi[i]=h[i];
}
int a[n];
for(int i=0;i<n;i++)a[i]=i;
sort(a,a+n,[&](int i,int j)->bool {
return h[i]<h[j];
});
for(int i=0;i<n;i++){
sort(v[i].begin(),v[i].end(),[&](int i,int j)->bool {
return h[i]<h[j];
});
}
int ans=0;
bool past[n];
memset(past,0,n);
for(int i=0;i<n;i++){
past[a[i]]=1;
for(int j:v[a[i]]){
if(past[j]){
ans+=fm(a[i])+fm(j);
unite(a[i],j);
}
}
}
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... |