其他分享
首页 > 其他分享> > [USACO17DEC]Barn Painting G 题解

[USACO17DEC]Barn Painting G 题解

作者:互联网

题面翻译

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

题目描述

Farmer John has a large farm with \(N\) barns (\(1 \le N \le 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 \(N\) 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 \(N\) and \(K\) (\(0 \le K \le N\)), respectively the number of barns on the farm and the number of barns that have already been painted.

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

The next \(K\) lines each contain two integers \(b\) and \(c\) (\(1 \le b \le N\), \(1 \le c \le 3\)) indicating that barn \(b\) is painted with color \(c\).

样例输入

4 1
1 2
1 3
1 4
4 3

样例输出

8

读完题发现树形dp味道很浓,但却不知如何下手,树上方案数表示我们可以使用一个二维数组 \(f[i][j]\) 表示节点为 \(i\) ,染色情况为 \(j\) 时的方案数

有转移方程:

\(f[u][0]=f[u][0]*(f[son[i]][1]+f[son[i]][2])\)

\(f[u][1]=f[u][1]*(f[son[i]][0]+f[son[i]][2])\)

\(f[u][2]=f[u][2]*(f[son[i]][0]+f[son[i]][1])\)

巧用树上节点不能染色相同的性质

Code.

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e6+10,mod=1e9+7;
int n,k,h[N],ne[N],e[N],idx,dp[4][N];
void add(int u,int v)
{
	ne[++idx]=h[u],e[idx]=v,h[u]=idx;
}
void dfs(int u,int father)
{
	for(int i=1;i<=3;i++)
	{
		if(dp[i][u])
		{
			for(int j=1;j<i;j++) dp[j][u]=0;
			break;
		}
		dp[i][u]=1;
	}
	for(int i=h[u];~i;i=ne[i])
	{
		int j=e[i];
		if(e[i]==father) continue ;
		else
		{
			dfs(j,u);
			dp[1][u]=dp[1][u]*(dp[2][j]+dp[3][j])%mod;
			dp[2][u]=dp[2][u]*(dp[1][j]+dp[3][j])%mod;
			dp[3][u]=dp[3][u]*(dp[1][j]+dp[2][j])%mod;
		}
	}
}
signed main()
{
	scanf("%lld%lld",&n,&k);
	memset(h,-1,sizeof h);
	for(int i=1;i<n;i++)
	{
		int u,v;
		scanf("%lld%lld",&u,&v);
		add(u,v),add(v,u);
	}
	for(int i=1;i<=k;i++)
	{
		int a,b;
		scanf("%lld%lld",&a,&b);
		dp[b][a]=1; 
	}
	dfs(1,0);
	printf("%lld",(dp[1][1]+dp[2][1]+dp[3][1])%mod);
	return 0;
}

标签:le,barns,int,题解,USACO17DEC,two,son,painted,Painting
来源: https://www.cnblogs.com/EastPorridge/p/16365003.html