Submission #854866

#TimeUsernameProblemLanguageResultExecution timeMemory
854866noyancanturkSjekira (COCI20_sjekira)C++17
110 / 110
47 ms9748 KiB
#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 timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...