链接:https://www.nowcoder.com/acm/contest/141/G
来源:牛客网
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.
The first line of input contains three space-separated integer N, K, D indicating the number of vertices, number of colors, and the required colorness. For each following N-1 lines, each contains two space-separated positive integer ui, vi indicating that there's an edge between ui and vi. 1 ≤ K < N ≤ 5000 1 ≤ D ≤ N 1 ≤ ui < vi ≤ N It's guaranteed that the given input is a tree.
Output one line contains an integer indicating the number of way module 1000000007(109+7) to color the tree resulting in colorness being D.
示例1
复制
2 1 1 1 2
复制
1
示例2
复制
4 3 2 1 2 2 3 3 4
复制
18
示例3
复制
4 3 2 1 2 1 3 1 4
复制
24
题目大意:有一棵n个结点的树,现在要对这n个结点进行染色,总共有k中颜色可以选择。现在定义一棵树的颜色度数为两个相同颜色的结点之间的最小距离,现在要你求出颜色度数为d 的染色方案数有多少种,最终结果对1e9+7取模。
题目思路:对于本题,我们定义F(x)为树上颜色相同的两点的最小距离大于x的方案数,那么我们所要求的结果就是F(d-1)-F(d)。
我们要怎么求F(x)呢。我们以bfs对每个点的情况进行遍历,对于每个结点,我们可以做一遍dfs,统计一下与该结点距离小于等于x同时已经染上颜色的结点个数num,如果num>=k,说明无法对当前节点进行染色,就直接返回0,如果num 具体实现看代码: #include