Good DFS problem.
Solution #
We need to calculate (sum of all the numbers in the subtree of vertex ) and and (the maximum and second maximum from all in the subtree of vertex except ). Update answer after calculating and for each vertex. This can be done using one DFS, refer to my code for the detailed implementation.
Code #
#include <bits/stdc++.h>
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
#define for1(i, n) for (int i = 1; i <= (int)(n); ++i)
#define fore(i, l, r) for (int i = (int)(l); i <= (int)(r); ++i)
#define ford(i, n) for (int i = (int)(n)-1; i >= 0; --i)
#define pb push_back
#define ms(a, x) memset(a, x, sizeof(a))
#define F first
#define S second
#define endl '\n'
using namespace std;
typedef long long ll;
const ll INF = 1e18+1;
typedef pair<int, int> pii;
const int N=2e5+5;
vector<int> G[N];
ll a[N],sum[N],mx[N];
ll ans=-INF;
void dfs1(int v,int p){
sum[v]=a[v];
mx[v]=-INF;
ll m1=-INF,m2=-INF;
for(auto it:G[v]){
if(it==p) continue;
dfs1(it,v);
sum[v]+=sum[it];
mx[v]=max(mx[v],mx[it]);
ll val=mx[it];
if(val>m1) swap(m1,val);
if(val>m2) swap(m2,val);
}
if(m2> -INF) ans=max(ans,m1+m2);
mx[v]=max(mx[v],sum[v]);
return;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin>>n;
for1(i,n){
cin>>a[i];
}
forn(i,n-1){
int u,v;
cin>>u>>v;
G[u].emplace_back(v);
G[v].emplace_back(u);
}
dfs1(1,1);
if(ans==-INF) cout<<"Impossible";
else cout<<ans;
return 0;
}