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
| #include<bits/stdc++.h> using namespace std; #define ll long long const int N = 1e5+10; int d[N],u[N]; int son[N]; int a[N],b[N]; vector<int>g[N]; int n; void add(int s,int t){ g[s].push_back(t); } bool dfs(int s,int fa){ int down = 0, up = 1; for(auto t : g[s]){ if(t==fa)continue; if(!dfs(t,s))return false; down += d[t]; up += u[t]; } d[s] = max(d[s], down); u[s] = min(u[s], up); return d[s] <= u[s]; } void getson(int u,int fa){ son[u] = 1; for(auto v : g[u]){ if(v==fa)continue; getson(v,u); son[u]+=son[v]; } } bool check(int mid){ for(int i=1;i<=n;i++){ u[i] = min(son[i],mid-b[i]); if(u[i]<0)return false; } return dfs(1,0)&&mid>=d[1]&&mid<=u[1]; } void solve(){ scanf("%d",&n); for(int i=1;i<=n;i++){ g[i].clear(); son[i]=0; d[i]=0; u[i]=0; b[i]=0; a[i]=0; } for(int i=1;i<n;i++){ int u,v; scanf("%d%d",&u,&v); add(u,v); add(v,u); } getson(1,0); int na; scanf("%d",&na); bool flag = 1; for(int i=1;i<=na;i++){ int x,y; scanf("%d%d",&x,&y); a[x] = y; d[x] = max(d[x],y); if(son[x]<d[x])flag = 0; } int nb; scanf("%d",&nb); for(int i=1;i<=nb;i++){ int x,y; scanf("%d%d",&x,&y); b[x]=max(b[x],y); if(y>n-son[x])flag = 0; } if(!flag){ printf("-1\n"); return ; } int l = 0, r = n; int ans = - 1; while(l<=r){ int mid = (l+r)>>1; if(check(mid)){ r = mid - 1; ans = mid; }else{ l = mid + 1; } } printf("%d\n",ans); } int main(){ int t; scanf("%d",&t); while(t--)solve(); }
|