【NOIP模擬賽】林下風氣

在這裏插入圖片描述

題解 :

dp維護亂搞,強行枚舉最小值,然後算出聯通塊滿足的值f[i][1]和不滿足的值f[i][0];

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=3350,P=19260817;
int n,k,rt,num;
int a[N],last[N];
ll f[N][2],ans;
struct edge {
	int to,next;
} e[2*N];
void add(int x,int y) {
	e[++num].to=y;
	e[num].next=last[x];
	last[x]=num;
}
void dfs(int x,int fa) {
	if(a[x]==a[rt]+k) f[x][1]=1,f[x][0]=0;
	else f[x][1]=0,f[x][0]=1;
	for(int w=last[x]; w; w=e[w].next) {
		int y=e[w].to;
		if(y==fa||a[y]==a[rt]&&y>rt||a[y]<a[rt]||a[y]>a[rt]+k) continue;
		dfs(y,x);
		f[x][1]=(f[x][1]+f[x][1]*f[y][0]%P+f[x][0]*f[y][1]%P+f[x][1]*f[y][1]%P)%P;
		f[x][0]=(f[x][0]+f[x][0]*f[y][0]%P)%P;
	}
}
int read(){
	int num=0;
	char ch=getchar();
	while(ch>'9'||ch<'0'){
		ch=getchar();
	}
	while(ch>='0'&&ch<='9'){
		num=(num<<1)+(num<<3)+ch-'0';
		ch=getchar();
	}
	return num;
}
int main() {
	n=read(),k=read();
	for(int i=1;i<=n;i++) 
		a[i]=read();
	for(int i=1;i<n;i++){
		int x=read(),y=read();
		add(x,y),add(y,x);
	}
	for(int i=1;i<=n;i++) 
		rt=i,dfs(rt,0),ans=(ans+f[i][1])%P;
	printf("%lld",ans);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章