1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
|
#include<bits/stdc++.h> using namespace std;
using ll=long long;
constexpr int N=5e5+5;
vector<int> e[N]; int n,K; int h[N],s[N]; int pos[N]; int ans=1e9; struct tree{ int l[N<<2]; int r[N<<2]; int lz[N<<2]; int minn[N<<2]; void pushup(int x){ minn[x]=min(minn[x<<1],minn[x<<1|1]); } void build(int x,int L,int R){ l[x]=L; r[x]=R; if(L==R){ minn[x]=-L; return; } int mid=L+R>>1; build(x<<1,L,mid); build(x<<1|1,mid+1,R); pushup(x); return; } void pushdown(int x){ if(lz[x]){ int k=lz[x]; minn[x<<1]+=k; lz[x<<1]+=k; minn[x<<1|1]+=k; lz[x<<1|1]+=k; lz[x]=0; } return; } void add(int x,int L,int R,int k){ if(L>R) return; if(l[x]>=L&&r[x]<=R){ minn[x]+=k; lz[x]+=k; return; } pushdown(x); if(r[x<<1]>=L) add(x<<1,L,R,k); if(l[x<<1|1]<=R) add(x<<1|1,L,R,k); pushup(x); return; } int find(int x){ if(l[x]==r[x]) return l[x]; pushdown(x); if(minn[x<<1]<0) return find(x<<1); else return find(x<<1|1); } }tr;
void dfs(int x,int fa,int minn){ pos[x]=[&]{ int l=1,r=K,res=K+1; while(l<=r){ int mid=l+r>>1; if(s[mid]<=minn) res=mid,r=mid-1; else l=mid+1; } return res; }(); for(auto v:e[x]){ if(v==fa) continue; dfs(v,x,min(minn,h[v])); } }
void add(int x,int fa,int minn){ int poss=[&]{ int l=1,r=K,res=K+1; while(l<=r){ int mid=l+r>>1; if(s[mid]<=minn) res=mid,r=mid-1; else l=mid+1; } return res; }(); tr.add(1,pos[x],K,-1); tr.add(1,poss,K,1); for(auto v:e[x]){ if(v==fa) continue; add(v,x,min(minn,h[v])); } }
void del(int x,int fa,int minn){ int poss=[&]{ int l=1,r=K,res=K+1; while(l<=r){ int mid=l+r>>1; if(s[mid]<=minn) res=mid,r=mid-1; else l=mid+1; } return res; }(); tr.add(1,pos[x],K,1); tr.add(1,poss,K,-1); for(auto v:e[x]){ if(v==fa) continue; del(v,x,min(minn,h[v])); } }
void dp(int x,int fa,int minn,int poss){ if(minn<s[poss]) return; if(h[x]<s[poss]){ add(x,fa,s[poss]); if(tr.minn[1]>=0) ans=min(ans,s[poss]-h[x]); del(x,fa,s[poss]); return; } for(auto v:e[x]){ if(v==fa) continue; dp(v,x,min(minn,h[x]),poss); } }
int main(){ ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
cin>>n; for(int i=1;i<=n;i++) cin>>h[i]; for(int i=1,x,y;i<n;i++){ cin>>x>>y; e[x].push_back(y); e[y].push_back(x); } cin>>K; for(int i=1;i<=K;i++) cin>>s[i]; sort(s+1,s+1+K,greater<int>()); tr.build(1,1,K); dfs(1,1,h[1]); for(int i=1;i<=n;i++) tr.add(1,pos[i],K,1); if(tr.minn[1]>=0){ cout<<"0"; return true&&false; } int poss=tr.find(1); dp(1,1,1e9,poss); if(ans==1e9) ans=-1; cout<<ans;
return true&&false; }
|