Codeforces 486D. Valid Sets
D. Valid Sets
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
As you know, an undirected connected graph with n nodes and n?-?1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. .Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109?+?7).
Input
The first line contains two space-separated integers d (0?≤?d?≤?2000) and n (1?≤?n?≤?2000).
The second line contains n space-separated positive integers a1,?a2,?...,?an(1?≤?ai?≤?2000).
Then the next n?-?1 line each contain pair of integers u and v (1?≤?u,?v?≤?n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
Copy
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
Copy
0 3
1 2 3
1 2
2 3
Output
3
Input
Copy
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1},?{2},?{3},?{4},?{1,?2},?{1,?3},?{3,?4} and {1,?3,?4}. Set {1,?2,?3,?4} is not valid, because the third condition isn't satisfied. Set {1,?4} satisfies the third condition, but conflicts with the second condition.
題解
直接統計不好統計,所以考慮把方案分類。
按照最大值點對方案分類,枚舉一個最大值點,讓這一個點在方案中,這樣就確定了方案能包含的連通塊。
設\(dp[i]\)表示一定包含i這個點且i這個點是方案中權值最大的點的方案,有
\[dp[i] = \prod (dp[son_i] + 1)\]
這樣會計算重。因為最大值點所確定的連通塊里,可能有多個與最大值點權值相同的點,每個點都會算一遍。
只算一個,然后乘以連通的相同值點的個數?
不!別忘了我們\(dp\)的時候,要求選定的點必須在方案中。必定包含不同的相同最大權值點的方案并不是一一對應的。
怎么辦?
繼續把方案分類。
在這個包含多個最大值點的極大連通塊里,設有\(k\)個相同的最大值點。
設最大的相同點編號為\(x\),\(dp\)必定包含點x的集合就行了。
這就相當于,我們只走比他編號小的相同權值的點。
兩次使用最大值分類方案的神題Orz
被long long 和 MOD卡了兩次。。
轉載于:https://www.cnblogs.com/huibixiaoxing/p/8535927.html
總結
以上是生活随笔為你收集整理的Codeforces 486D. Valid Sets的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 云阳武警中队在哪里?
- 下一篇: j2ee gradle构建