88 lines
1.9 KiB
C++
88 lines
1.9 KiB
C++
/// Gheorghies Alexandru
|
|
#include<bits/stdc++.h>
|
|
|
|
using namespace std;
|
|
typedef long long ll;
|
|
typedef long double ld;
|
|
typedef pair<ll,ll> pll;
|
|
typedef pair<ld,ld> pld;
|
|
|
|
|
|
const ll LGMAX=20,NMAX=5e5+5;
|
|
ll dp[NMAX],deg[NMAX];
|
|
vector<ll> edg[NMAX];
|
|
void tc(){
|
|
ll n,s=0,ans=LLONG_MAX;
|
|
cin>>n;
|
|
for(ll i=1;i<=n;i++) cin>>dp[i],s+=dp[i];
|
|
for(ll i=0;i<n;i++){
|
|
ll u,v; cin>>u>>v;
|
|
edg[u].push_back(v);
|
|
edg[v].push_back(u);
|
|
deg[u]++,deg[v]++;
|
|
}
|
|
queue<ll> q;
|
|
for(ll i=1;i<=n;i++)
|
|
if(deg[i]==1)
|
|
q.push(i);
|
|
while(!q.empty()){
|
|
deg[q.front()]=0;
|
|
ans=min(ans,abs(2*dp[q.front()]-s));
|
|
for(auto it : edg[q.front()]){
|
|
if(deg[it]>0){
|
|
dp[it]+=dp[q.front()];
|
|
deg[it]--;
|
|
if(deg[it]==1)
|
|
q.push(it);
|
|
}
|
|
}
|
|
q.pop();
|
|
}
|
|
vector<ll> cycle;
|
|
for(ll i=1;i<=n;i++){
|
|
if(deg[i]>0){
|
|
cycle={i};
|
|
deg[i]=0;
|
|
break;
|
|
}
|
|
}
|
|
while(1){
|
|
bool ok=0;
|
|
for(auto it : edg[cycle.back()]){
|
|
if(deg[it]){
|
|
cycle.push_back(it);
|
|
deg[it]=0;
|
|
ok=1;
|
|
break;
|
|
}
|
|
}
|
|
if(!ok) break;
|
|
}
|
|
n=cycle.size();
|
|
ll l=0,r=n-1,curr=0;
|
|
for(ll l=0;l<n;l++){
|
|
while(1){
|
|
ll nxt=cycle[(r+1)%n];
|
|
if((curr+dp[nxt])*2<=s)
|
|
curr+=dp[nxt],r=(r+1)%n;
|
|
else break;
|
|
}
|
|
ans=min(ans,abs(curr*2-s));
|
|
ll nxt=cycle[(r+1)%n];
|
|
ans=min(ans,abs((curr+dp[nxt])*2-s));
|
|
curr-=dp[cycle[l]];
|
|
}
|
|
cout<<ans;
|
|
}
|
|
int main()
|
|
{
|
|
#ifndef ONLINE_JUDGE
|
|
freopen("in.txt","r",stdin);
|
|
freopen("out.txt","w",stdout);
|
|
#endif // ONLINE_JUDGE
|
|
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
|
|
//ll t; cin>>t; while(t--)
|
|
tc();
|
|
return 0;
|
|
}
|