Coloring Tree (转化+bfs计数)

题面:
Christmas is coming! Eddy has received a Christmas tree as gift. Not surprisingly, the tree consists of N vertices and N-1 edges and magically remains connected. Currently, all the vertex of the tree is uncolored. Eddy wants to color each vertex into one of K colors. However, there are too many way to color the tree(i.e. KN ways). Eddy doesn’t want the result of coloring being too boring. Thus, he defines the colorness of a tree as follow:

The colorness of a tree is the minimum distance between two vertex colored in the same color.

Now, Eddy is wondering how many way to color the tree such that the colorness of the tree will be D.
题意: 给你一棵树,你可以对树进行染色,树的价值定义为最小的相同颜色的节点之间的距离,问你当树的价值为d的时候,有多少种染色方案。
思路:
我们可以转化一下题目,可以转变成当树的价值>=d时,有多少种方案,然后我们用>=d的方案数减去>=d+1的方案数 就是价值刚好为d的方案数了。
怎么求树的价值>=d的方案数呢?这里可以看成对于任意一个节点,所有和它距离小于d的节点,不能和它有相同的颜色。

#include
using namespace std;
typedef long long ll;
const int N=5005;
const int mod=1e9+7;
vector<int>G[N];
int n,k,d;
bool vis[N];
int dfs(int u,int pre,int dis)
{
	int res=0;
	if(dis<=0)
		return 0;
	for(auto v: G[u])
	{
		if(vis[v]&&v!=pre)
			res+=dfs(v,u,dis-1)+1;
	}
	return res;
}

ll sl(int d)
{
	ll res=1;
	memset(vis,0,sizeof vis);
	queue<int>que;
	que.push(1);
	while(!que.empty())
	{
		int u=que.front();
		vis[u]=1;
		que.pop();
		ll cnt=k-dfs(u,0,d);
		if(cnt<=0)
			return 0;
		res=res*cnt%mod;
		for(auto v: G[u])
		{
			if(!vis[v])
				que.push(v);
		}
	}
	return res;
}

int main()
{
	scanf("%d%d%d",&n,&k,&d);
	for(int i=1;i<n;i++)
	{
		int u,v;
		scanf("%d%d",&u,&v);
		G[u].push_back(v);
		G[v].push_back(u);
	}
	printf("%lld\n",(sl(d-1)-sl(d)+mod)%mod);
	return 0;
}

你可能感兴趣的:(搜索)