Tree Cutting (Hard Version) CodeForces - 1118F2 (树形DP,计数)

大意:给定树, 每个点有颜色, 一个合法的边集要满足删除这些边后, 每个连通块内颜色仅有一种, 求所有合法边集的个数

$f[x][0/1]$表示子树$x$中是否还有与$x$连通的颜色

对于每种颜色已经确定了一个连通块, 连通块内部一定不能断边, 有转移

$$f[x][1]=\prod (f[y][0]+f[y][1]),f[x][0]=0$$

能断边的部分只能为不同颜色连通块间的无色结点, 有转移

$$f[x][0]=\prod (f[y][0]+f[y][1]), f[x][1]=\sum\limits_y (f[y][1]\prod\limits_{z!=y}(f[z][0]+f[z][1])) $$

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <string.h>
#define REP(i,a,n) for(int i=a;i<=n;++i)
#define PER(i,a,n) for(int i=n;i>=a;--i)
#define hr putchar(10)
#define pb push_back
#define lc (o<<1)
#define rc (lc|1)
#define mid ((l+r)>>1)
#define ls lc,l,mid
#define rs rc,mid+1,r
#define x first
#define y second
#define io std::ios::sync_with_stdio(false)
#define endl '\n'
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int P = 998244353, INF = 0x3f3f3f3f;
ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;}
ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;}
//head
#ifdef ONLINE_JUDGE
const int N = 1e6+10;
#else
const int N = 111;
#endif

int n, k;
vector<int> g[N], q;
int col[N], c[N], cnt[N];
int f[N][2], prod[N];

void dfs(int x, int fa) {
	cnt[x] = col[x]>0;
	for (int y:g[x]) if (y!=fa) {
		dfs(y,x);
		if (!col[x]) col[x]=col[y];
		else if (col[y]&&col[x]!=col[y]) {
			puts("0"), exit(0);
		}
		cnt[x] += cnt[y];
	}
	q.clear();
	for (int y:g[x]) if (y!=fa) q.pb(y);
	prod[0] = 1;
	int sz = q.size();
	REP(i,0,sz-1) { 
		int y = q[i];
		prod[i+1]=(ll)prod[i]*(f[y][0]+f[y][1])%P;
	}
	if (col[x]) f[x][1]=prod[sz];
	else {
		f[x][0]=prod[sz];
		int tmp = 1;
		PER(i,0,sz-1) {
			int y = q[i];
			f[x][1] = (f[x][1]+(ll)tmp*f[y][1]%P*prod[i]%P)%P;
			tmp = (ll)tmp*(f[y][0]+f[y][1])%P;
		}
	}
	if (c[col[x]]==cnt[x]) cnt[x]=col[x]=0;
}


int main() {
	scanf("%d%d", &n, &k);
	REP(i,1,n) scanf("%d", col+i);
	REP(i,1,n) ++c[col[i]];
	REP(i,2,n) {
		int u, v;
		scanf("%d%d", &u, &v);
		g[u].pb(v),g[v].pb(u);
	}
	dfs(1,0);
	printf("%d\n", f[1][1]);
}

猜你喜欢

转载自www.cnblogs.com/uid001/p/10520954.html
今日推荐