이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define mp make_pair
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef long double ld;
template <typename T> bool chkmin(T &x,T y){return x>y?x=y,1:0;}
template <typename T> bool chkmax(T &x,T y){return x<y?x=y,1:0;}
int readint(){
int x=0,f=1; char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int n,a[100005],v[200005],nxt[200005],h[100005],tot,ord[100005],fa[100005],mx[100005];
vector<pii> edg;
set<pii> st;
ll ans=0;
void addedge(int x,int y){
v[++tot]=y; nxt[tot]=h[x]; h[x]=tot;
v[++tot]=x; nxt[tot]=h[y]; h[y]=tot;
}
void ins(int x,int y){
if(x>y) swap(x,y);
if(st.find(mp(x,y))!=st.end()) return;
st.insert(mp(x,y));
edg.pb(mp(x,y));
}
int getf(int x){return fa[x]==x?x:fa[x]=getf(fa[x]);}
void merge(int x,int y){
x=getf(x); y=getf(y);
ans+=mx[x];
ans+=mx[y];
fa[y]=x;
mx[x]=max(mx[x],mx[y]);
}
int main(){
n=readint();
for(int i=1;i<=n;i++) a[i]=readint();
for(int i=1;i<n;i++) addedge(readint(),readint());
for(int i=1;i<=n;i++) ord[i]=i;
sort(ord+1,ord+n+1,[&](int i,int j){return a[i]>a[j];});
for(int i=1;i<=n;i++){
int x=ord[i];
for(int p=h[x];p;p=nxt[p]) ins(x,v[p]);
}
reverse(edg.begin(),edg.end());
for(int i=1;i<=n;i++) fa[i]=i,mx[i]=a[i];
for(auto&p:edg) merge(p.fi,p.se);
printf("%lld\n",ans);
return 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... |