이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#pragma GCC optimize("unroll-loops,Ofast,O3")
#include <bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define spc << " " <<
#define endl "\n"
#define all(x) x.begin(), x.end()
#define ll long long
#define int long long
#define ii pair<int,int>
#define vi vector<int>
#define vii vector<ii>
#define st first
#define nd second
#define inf 1000000009
#define MOD 1000000007
#define lim 100005
using namespace std;
vi edges[lim];
int maxi[lim], val[lim], chop[lim], par[lim];
int ans=0;
ii rang[lim];
int timey=0;
void tour(int node){
timey++;
rang[node] = {timey,timey};
for(auto i:edges[node]){
if(i==par[node]) continue;
tour(i);
rang[node].nd = rang[i].nd;
}
}
void dfs(int node){
maxi[node] = val[node];
for(auto i:edges[node]){
if(i==par[node]) continue;
par[i]=node;
dfs(i);
maxi[node] = max(maxi[node], maxi[i]);
}
}
void calc(int node){
chop[node]=1;
for(auto i:edges[node]){
if(chop[i] || i==par[node]) continue;
ans += val[node] + maxi[i];
calc(i);
}
}
int vis[lim];
void wtf(int node){
if(vis[node]) return;
vis[node]=1;
for(auto i:edges[node]){
if(i==par[node]) continue;
wtf(i);
}
}
void solve(){
int n; cin >> n;
vii next(n);
for(int i=1; i<=n; i++){
chop[i]=vis[i]=0;
int a; cin >> a;
val[i]=a;
next[i-1] = {a, i};
}
sort(all(next), greater<ii>());
for(int i=1; i<n; i++){
int a,b; cin >> a >> b;
edges[a].pb(b);
edges[b].pb(a);
}
par[1]=0;
dfs(1);
tour(1);
int ptr=0;
int wow[n+1];
for(int i=1; i<=n; i++) wow[i]=-1;
for(int i=0; i<n; i++){
ii cur = next[i];
wtf(cur.nd);
while(ptr<n && ((rang[next[ptr].nd].st>=rang[cur.nd].st && rang[next[ptr].nd].st<=rang[cur.nd].nd) || vis[next[ptr].nd]==1)) ptr++;
if(ptr>=n) break;
wow[cur.nd] = next[ptr].st;
}
/*for(auto cur:next){
cerr << cur.nd spc ":" spc cur.st spc wow[cur.nd] << endl;
}*/
for(int j=0; j<n; j++){
ii cur = next[j];
if(cur.nd==1){
for(auto i:edges[1]){
if(chop[i]==0){
ans += maxi[i] + val[1];
calc(i);
}
}
break;
}
if(chop[cur.nd]==0){
//cerr << cur.nd << " ";
if(wow[cur.nd]!=-1) ans += cur.st + wow[cur.nd];
/*else{
cerr << "found one" spc cur.nd;
}*/
calc(cur.nd);
}
}
cout << ans << endl;
}
signed main(){
ios_base::sync_with_stdio(false);cin.tie(0);
#ifdef Local
freopen("in","r",stdin);
freopen("out","w",stdout);
#endif
ll 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... |