题目描述
Farmer John has a large farm with NN barns (1 \le N \le 10^51≤N≤10
5
), some of which are already painted and some not yet painted. Farmer John wants to paint these remaining barns so that all the barns are painted, but he only has three paint colors available. Moreover, his prize cow Bessie becomes confused if two barns that are directly reachable from one another are the same color, so he wants to make sure this situation does not happen.

It is guaranteed that the connections between the NN barns do not form any ‘cycles’. That is, between any two barns, there is at most one sequence of connections that will lead from one to the other.

How many ways can Farmer John paint the remaining yet-uncolored barns?

输入格式
The first line contains two integers NN and KK (0 \le K \le N0≤K≤N), respectively the number of barns on the farm and the number of barns that have already been painted.

The next N-1N−1 lines each contain two integers xx and yy (1 \le x, y \le N, x \neq y1≤x,y≤N,x≠y) describing a path directly connecting barns xx and yy.

The next KK lines each contain two integers bb and cc (1 \le b \le N1≤b≤N, 1 \le c \le 31≤c≤3) indicating that barn bb is painted with color cc.

输出格式
Compute the number of valid ways to paint the remaining barns, modulo 10^9 + 710
9
+7, such that no two barns which are directly connected are the same color.

题意翻译
题意:给定一颗N个节点组成的树,3种颜色,其中K个节点已染色,要求任意两相邻节点颜色不同,求合法染色方案数。 翻译贡献者:Il_ItzABC_lI

输入输出样例
输入 #1复制

4 1
1 2
1 3
1 4
4 3
输出 #1复制
8


树形dp即可。

我们 dp[i][j] 表示当前在i节点,颜色为j的方案数,那么如果这个节点已经固定了,那么我们就需要把其他的颜色方案数即为0.


AC代码:

#pragma GCC optimize(2)
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e5+10,p=1e9+7;
int n,k,dp[N][4],vis[N];
int head[N],nex[N<<1],to[N<<1],tot;
inline void add(int a,int b){
	to[++tot]=b; nex[tot]=head[a]; head[a]=tot;
}
void dfs(int x,int fa){
	if(vis[x])	dp[x][vis[x]]=1;
	else	dp[x][1]=dp[x][2]=dp[x][3]=1;
	for(int i=head[x];i;i=nex[i]){
		if(to[i]==fa)	continue;
		dfs(to[i],x);
		dp[x][1]=dp[x][1]*((dp[to[i]][2]+dp[to[i]][3])%p)%p;
		dp[x][2]=dp[x][2]*((dp[to[i]][1]+dp[to[i]][3])%p)%p;
		dp[x][3]=dp[x][3]*((dp[to[i]][1]+dp[to[i]][2])%p)%p;
	}
}
signed main(){
	cin>>n>>k;
	for(int i=1,a,b;i<n;i++)	scanf("%lld %lld",&a,&b),add(a,b),add(b,a);
	for(int i=1,a,b;i<=k;i++)	scanf("%lld %lld",&a,&b),vis[a]=b;
	dfs(1,1);	printf("%lld\n",(dp[1][1]+dp[1][2]+dp[1][3])%p);
	return 0;
}