DZY Loves Connecting
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total Submission(s): 332 Accepted Submission(s): 112
Problem Description
DZY has an unrooted tree consisting of n nodes labeled from 1 to n. DZY likes connected sets on the tree. A connected set S is a set of nodes, such that every two nodes u,v in S can be connected by a path on the tree, and the path should only contain nodes from S. Obviously, a set consisting of a single node is also considered a connected set. The size of a connected set is defined by the number of nodes which it contains. DZY wants to know the sum of the sizes of all the connected sets. Can you help him count it? The answer may be large. Please output modulo 109+7.
Input
First line contains t denoting the number of testcases. t testcases follow. In each testcase, first line contains n. In lines 2∼n, ith line contains pi, meaning there is an edge between node i and node pi. ( 1≤pi≤i−1,2≤i≤n) ( n≥1。 sum of n in all testcases does not exceed 200000)
Output
Output one line for each testcase, modulo 109+7.
Sample Input
2 1 5 1 2 2 3
Sample Output
1 42
Hint
In the second sample, the 4 edges are (1,2),(2,3),(2,4),(3,5). All the connected sets are {1},{2},{3},{4},{5},{1,2},{2,3},{2,4},{3,5},{1,2,3},{1,2,4},{2,3,4},{2,3,5},{1,2,3,4},{1,2,3,5},{2,3,4,5},{1,2,3,4,5}. If you need a larger stack size, please use #pragma comment(linker, "/STACK:102400000,102400000") and submit your solution using C++. Source
一个挺直接的树DP。之前TC的一个原题,。比赛时死活没啃出来。。
。太嫩了……
题目大意:给出一个树,详细建法就不细说了。每一个点贡献为1,问树上全部不同集合的合计贡献。
首先对于每一个点,我们能够求出它所在的集合数量。
开个数组cnt。表示第i个点在其子树中所在的集合数。这样cnt[i]就等于i全部孩子的cnt+1的乘积。事实上这里用到了组合,从全部孩子中能够随意选择一定的集合(+1表示空集)进行组合。
求出集合数是为了求贡献,遍历到i的某个孩子的时候,新添加的贡献事实上就是之前的全部贡献乘上该孩子的集合数+1(选择某些集合组合),然后对于之前遍历的子数。该孩子也能够提供贡献,也就是该孩子的贡献乘上当前出现的集合数。
口述表达的不好,也不会做那种图。
。还是看代码吧,就俩公式。。
代码例如以下:
#include#include #include #include #include #include #include #include #include #include
#include