Appleman and Tree CodeForces - 461B(树形dp)
Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.
Consider a set consisting of k (0?≤?k?<?n) edges of Appleman’s tree. If Appleman deletes these edges from the tree, then it will split into (k?+?1) parts. Note, that each part will be a tree with colored vertices.
Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109?+?7).
Input
The first line contains an integer n (2??≤?n?≤?105) — the number of tree vertices.
The second line contains the description of the tree: n?-?1 integers p 0,?p 1,?…,?p n?-?2 (0?≤?p i?≤?i). Where p i means that there is an edge connecting vertex (i?+?1) of the tree and vertex p i. Consider tree vertices are numbered from 0 to n?-?1.
The third line contains the description of the colors of the vertices: n integers x 0,?x 1,?…,?x n?-?1 ( x i is either 0 or 1). If x i is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white.
Output
Output a single integer — the number of ways to split the tree modulo 1000000007 (109?+?7).
Examples
Input
3
0 0
0 1 1
Output
2
Input
6
0 1 1 0 4
1 1 0 0 1 0
Output
1
Input
10
0 1 2 1 4 4 4 0 8
0 0 0 1 0 1 1 0 0 1
Output
27
dp數(shù)組的每一種狀態(tài)代表著什么,并且每一種狀態(tài)之間如何轉(zhuǎn)換是解決dp問題的關(guān)鍵之處。
思路:
dp[i][0]代表著以i為父節(jié)點的樹,沒有黑點的狀態(tài)數(shù)目。
dp[i][1]代表著以i為父節(jié)點的數(shù),有1個黑點的狀態(tài)數(shù)目。
狀態(tài)轉(zhuǎn)移方程:
①如果當(dāng)前節(jié)點是黑色,父親節(jié)點也是黑色,那么只能斷開,只對dp[u][1]有貢獻(xiàn)。
②如果當(dāng)前節(jié)點是黑色,父親節(jié)點是白色,可以與父親節(jié)點合并,也可以與父親節(jié)點斷開,對dp[u][0]和dp[u][1]同時有貢獻(xiàn)。
③如果當(dāng)前節(jié)點是白色,父節(jié)點是黑色,只能合并,對dp[u][1]有貢獻(xiàn)。
④如果當(dāng)前節(jié)點是白色,父親節(jié)點是白色,只能合并,對dp[u][0]有貢獻(xiàn)。
最終輸出dp[0][1]就可以。
代碼如下:
努力加油a啊,(o)/~
總結(jié)
以上是生活随笔為你收集整理的Appleman and Tree CodeForces - 461B(树形dp)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 5g的一个重要技术特点
- 下一篇: Yet Another Counting