Submission #870871

#TimeUsernameProblemLanguageResultExecution timeMemory
870871epicci23Sjekira (COCI20_sjekira)C++17
110 / 110
65 ms19648 KiB
#include "bits/stdc++.h"
using namespace std;
#define pb push_back
#define endl "\n" 
#define int long long
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()

/* stuff you should look for
 * int overflow, array bounds
 * special cases (n=1?)
 * do smth instead of nothing and stay organized
 * WRITE STUFF DOWN
 * DON'T GET STUCK ON ONE APPROACH
 * SIMPLIFY THE PROBLEM
 * READ THE STATEMENT CAREFULLY
  !!! if there is an specified/interesting smth(i.e. constraint) in the statement,
  then you must be careful about that   
*/

const int N = 1e5 + 5;

int ar[N],par[N],ans=0;
vector<int> v[N],v2[N],vis(N,0);

int find(int a){
  if(par[a]==a) return a;
  return par[a]=find(par[a]);
}

void unite(int a,int b){
  a=find(a),b=find(b);
  if(ar[a]>ar[b]) swap(a,b);
  par[a]=b;
}

void dfs(int c,int p){
  ans += sz(v2[c]) * ar[c];
  for(int x:v2[c]){
  	if(x==p) continue;
  	dfs(x,c);
  }
}

void solve(){
  iota(par,par+N,0LL);
  int n;
  cin >> n;
  for(int i=1;i<=n;i++) cin >> ar[i];
  for(int i=1;i<n;i++){
  	int a,b;
  	cin >> a >> b;
  	v[a].pb(b);
  	v[b].pb(a);
  }
  vector<array<int,2>> xd;

  for(int i=1;i<=n;i++) xd.pb({ar[i],i});

  sort(all(xd));

  for(auto x:xd){
    int a = x[1];
    vis[a] = 1;
    for(int u : v[a]){
      if(!vis[u]) continue;
      v2[a].pb(find(u));
      v2[find(u)].pb(a);
      unite(a,u);
    }
  }

  dfs(1,0);

  cout << ans << endl;
}

int32_t main(){

  cin.tie(0); ios::sync_with_stdio(0);
  
  int t=1;//cin >> t;
  while(t--) solve();

  return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...