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 ;
const int MAX = 1e5 + 10 ;
int arr[MAX] ;
int n ;
vector< vector<int> >adj(MAX) ;
vector< pair<int , int> >vp ;
int par[MAX] , sz[MAX] , val[MAX] ;
int mark[MAX] ;
void init()
{
for(int i = 1 ; i <= n ; ++i)
par[i] = i , sz[i] = 1 , val[i] = arr[i] ;
}
int root(int node)
{
if(par[node] == node)
return node ;
return (par[node] = root(par[node])) ;
}
void Union(int x , int y)
{
int a = root(x) ;
int b = root(y) ;
if(sz[a] < sz[b])
swap(a , b) ;
par[b] = a ;
sz[a] += sz[b] ;
val[a] = max(val[a] , val[b]) ;
}
int main()
{
ios_base::sync_with_stdio(0) ;
cin.tie(0) ;
cin>>n ;
for(int i = 1 ; i <= n ; ++i)
{
cin>>arr[i] ;
vp.emplace_back(arr[i] , i) ;
}
for(int i = 0 ; i < n-1 ; ++i)
{
int x , y ;
cin>>x>>y ;
adj[x].push_back(y) ;
adj[y].push_back(x) ;
}
init() ;
sort(vp.begin() , vp.end()) ;
long long ans = 0 ;
for(auto &p : vp)
{
int node = p.second ;
mark[node] = 1 ;
for(auto &child : adj[node])
{
if(mark[child])
ans += arr[node] + val[root(child)] ;
}
for(auto &child : adj[node])
{
if(mark[child])
Union(node , child) ;
}
}
return cout<<ans<<"\n" , 0 ;
}
# | 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... |