题目链接:http://codeforces.com/contest/486/problem/D
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
1 4 2 1 3 2 1 2 1 3 3 4
output
8
input
0 3 1 2 3 1 2 2 3
output
3
input
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.
题意:在一棵树上寻找一些点构成联通分块,该联通分块中的最大值减去最小值的值小于等于d,问有多少个这样的联通分块。
解题思路:从1到n,每次以i为树根,向下遍历,当遇到结点的值小于树根的值或者大于树根的值+d时(跳过这次遍历,假设树根的值为num,那么这棵树中所有的值在[num,num+d]之间),如果遇到结点的值和树根的值相同,那么只能从小到大遍历。
计算树的联通分量的状态转移方程为:f[x]=f[x]*(f[y]+1)。(其中y为x的子结点)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define LL long long
#define MOD 1000000007
#define N 2005
int n, d;
vector<int>g[N];
int a[N], idx, num;
LL dp[N];
void dfs(int x, int fa){
dp[x]=1;
int y;
for(int i=0;i<g[x].size();++i){
y=g[x][i];
if(y==fa) continue;
if(a[y]<num || a[y]>num+d) continue;
if(a[y]==num && y<idx) continue;
dfs(y,x);
dp[x]=(dp[x]*(dp[y]+1))%MOD;
}
}
int main()
{
LL ans=0;
int u, v;
scanf("%d%d",&d,&n);
for(int i=1;i<=n;++i) scanf("%d",&a[i]);
for(int i=1;i<n;++i){
scanf("%d%d",&u,&v);
g[u].push_back(v);
g[v].push_back(u);
}
for(int i=1;i<=n;++i){
memset(dp,0,sizeof(dp));
idx=i, num=a[i];
dfs(i,0);
ans=(ans+dp[i])%MOD;
}
cout<<ans;
return 0;
}