版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qkoqhh/article/details/82664995
树DP可以维护有没有黑点数为y的联通块,但不能保证点数,所以多一维肯定是炸了。。
然而有个显然的结论是,如果点数为x的黑点数最小为min,最大为max,那么[min,max]这个区间的黑点数一定存在
所以只需要维护点数为x的最小黑点和最大黑点就可以了。。
然后树背包dp随便转移,复杂度O(n^2)
/**
* ┏┓ ┏┓
* ┏┛┗━━━━━━━┛┗━━━┓
* ┃ ┃
* ┃ ━ ┃
* ┃ > < ┃
* ┃ ┃
* ┃... ⌒ ... ┃
* ┃ ┃
* ┗━┓ ┏━┛
* ┃ ┃ Code is far away from bug with the animal protecting
* ┃ ┃ 神兽保佑,代码无bug
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<cmath>
#include<map>
#include<stack>
#include<set>
#include<bitset>
#define inc(i,l,r) for(int i=l;i<=r;i++)
#define dec(i,l,r) for(int i=l;i>=r;i--)
#define link(x) for(edge *j=h[x];j;j=j->next)
#define mem(a) memset(a,0,sizeof(a))
#define ll long long
#define eps 1e-12
#define succ(x) (1<<x)
#define lowbit(x) (x&(-x))
#define sqr(x) ((x)*(x))
#define mid (x+y>>1)
#define NM 5005
#define nm 10005
#define pi 3.1415926535897931
const ll inf=1e9;
using namespace std;
ll read(){
ll x=0,f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch))x=x*10+ch-'0',ch=getchar();
return f*x;
}
struct edge{int t;edge*next;}e[nm],*h[NM],*o=e;
void add(int x,int y){o->t=y;o->next=h[x];h[x]=o++;}
int n,m,_x,_y,d[NM][NM],g[NM][NM],a[NM],f[NM],size[NM];
void dfs(int x){
d[x][1]=g[x][1]=a[x]==1;
size[x]=1;
inc(i,2,n)g[x][i]=inf;
link(x)if(f[x]!=j->t){
f[j->t]=x;
dfs(j->t);
size[x]+=size[j->t];
dec(v,size[x],2)inc(k,max(1,v+size[j->t]-size[x]),min(size[j->t],v-1))
d[x][v]=max(d[x][v],d[x][v-k]+d[j->t][k]),
g[x][v]=min(g[x][v],g[x][v-k]+g[j->t][k]);
}
}
int main(){
int _=read();while(_--){
mem(e);mem(h);o=e;mem(d);
n=read();m=read();
inc(i,2,n){_x=read();_y=read();add(_x,_y);add(_y,_x);}
inc(i,1,n)a[i]=read();
dfs(1);
inc(i,2,n)inc(j,1,size[i])d[1][j]=max(d[1][j],d[i][j]),g[1][j]=min(g[1][j],g[i][j]);
while(m--){
_x=read();_y=read();
puts(g[1][_x]<=_y&&_y<=d[1][_x]?"YES":"NO");
}
printf("\n");
}
return 0;
}
5072: [Lydsy1710月赛]小A的树
题目描述
给出一棵n个点的树,每个点有黑白两种颜色。q次询问,每次询问给出x和y,问能否选出一个x个点的联通子图,使得其中黑点数目为y。
输入
第一行一个正整数 T 表示数据组数。
对于每一组数据,第一行有两个用空格隔开的正整数,分别是 n 和 q ,表示树的节点数和询问次数。
接下来 n-1 行,每行两个用空格隔开的正整数和,表示和间有一条边相连。
接下来一行有 n 个用空格隔开的整数,其中若,则表示第 i 个点为白色,否则为黑色。
接下来 q 行,每行两个用空格隔开的整数 x 和 y 。
n<=5000,q<=10^5
输出
对于每一组数据,输出 q 行,每行为 “YES” 或者 “NO” (不含双引号),表示对于给定的和,能否满足小A 的要求。
每相邻两组数据的输出之间空一行。
样例输入
1
9 4
4 1
1 5
1 2
3 2
3 6
6 7
6 8
9 6
0 1 0 1 0 0 1 0 1
3 2
7 3
4 0
9 5
输出
YES
YES
NO
NO