链接:https://ac.nowcoder.com/acm/contest/33190/D
来源:牛客网
题目描述
One day, when NIO was walking under the tree, he found that there are birds standing on the tree, and each bird is standing on one leaf. He wondered about in how many sub-trees form by connected vertex-induced subgraphs from the original tree, all birds are in the same gender. The number would be very large, just mod 10^9+7 in the output.
输入描述:
There are multiple input cases.
For each case, the first line contains an integer, n, denoting the number of nodes on the tree. The second line is a binary string, where 1 denotes the male birds and 000 denotes the female birds.
Following by n−1 lines. In each line there are two integers, xi,yi , denoting there is a path connecting node x and node y.
1≤n≤3×105,1≤xi,yi≤N
输出描述:
Output a number module 10^9+7, the number of subgraphs of the given tree that form trees where all its leaves are the same color.
示例1
输入
复制
7
1011111
1 2
1 3
2 4
3 5
2 6
4 7
输出
复制
28
题目大意:
给定包含n个节点的树,每个节点具有颜色0或颜色1。求其有多少联通子图,满足度数为1的节点颜色相同。
举个例子:
举个例子,比如!左子树有100种方案,中子树有200种方案,右子树有400种方案,试问总方案Ans是多少?这题答案应该是(Ans1+1)(Ans2+1)(Ans3+1)即101201301=6110601种。
解决方案:
一般要选择的方案是树形DP兼以DFS的运用一个DFS下去,顺便将DP也包办了。但题目中,要注意一点结果要与10^9+7求模,所以,应该边算边模。同时,鸟分雌雄,可以将鸟的雌雄理解为染色,即整张图只有0或1两种颜色。这使难度减小大大的。
至于具体做法我放在代码中,每一行都有注释。
参考公式:
d p x , c = ∏ s ∈ S o n x ( 1 + d p s , c ) dp_{x,c}=\prod_{s\in Son_x}(1+dp_{s,c}) dpx,c=s∈Sonx∏(1+