容易猜到能选择的黑点个数是一个连续区间。那么设f[i][j]为i子树内选j个点形成包含根的连通块,最多有几个黑点,g[i][j]为最少有几个黑点,暴力dp是O(n)的,求出每个连通块大小对应的黑点数量取值范围即可。
惊觉差点不会树形背包了。注意不要出现任何非法转移,即使看上去无伤大雅。
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define N 5010
char getc(){char c=getchar();while ((c<'A'||c>'Z')&&(c<'a'||c>'z')&&(c<''||c>'')) c=getchar();return c;}
int gcd(int n,int m){return m==?n:gcd(m,n%m);}
int read()
{
int x=,f=;char c=getchar();
while (c<''||c>'') {if (c=='-') f=-;c=getchar();}
while (c>=''&&c<='') x=(x<<)+(x<<)+(c^),c=getchar();
return x*f;
}
int T,n,m,a[N],p[N],size[N],f[][N][N],l[N],r[N],t;
struct data{int to,nxt;
}edge[N<<];
void addedge(int x,int y){t++;edge[t].to=y,edge[t].nxt=p[x],p[x]=t;}
void dfs(int k,int from)
{
int s=;size[k]=;
for (int i=p[k];i;i=edge[i].nxt)
if (edge[i].to!=from) dfs(edge[i].to,k),s+=size[edge[i].to];
for (int i=;i<=s;i++) f[][k][i]=f[][k][i]=;
f[][k][]=a[k],f[][k][]=a[k]^;
for (int i=p[k];i;i=edge[i].nxt)
if (edge[i].to!=from)
{
size[k]+=size[edge[i].to];
for (int j=size[k];j>=;j--)
for (int x=max(,j-size[edge[i].to]);x<=min(size[k]-size[edge[i].to],j);x++)
f[][k][j]=max(f[][k][j],f[][k][x]+f[][edge[i].to][j-x]),
f[][k][j]=max(f[][k][j],f[][k][x]+f[][edge[i].to][j-x]);
}
for (int i=;i<=size[k];i++) l[i]=min(l[i],i-f[][k][i]);
for (int i=;i<=size[k];i++) r[i]=max(r[i],f[][k][i]);
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("bzoj5072.in","r",stdin);
freopen("bzoj5072.out","w",stdout);
const char LL[]="%I64d\n";
#else
const char LL[]="%lld\n";
#endif
T=read();
while (T--)
{
n=read(),m=read();
memset(p,,sizeof(p));t=;
for (int i=;i<n;i++)
{
int x=read(),y=read();
addedge(x,y),addedge(y,x);
}
for (int i=;i<=n;i++) a[i]=read(),l[i]=n+,r[i]=;
dfs(,);
while (m--)
{
int x=read(),y=read();
if (l[x]<=y&&r[x]>=y) puts("YES");
else puts("NO");
}
cout<<endl;
}
return ;
}