D. Valid Sets
Time Limit: 20 Sec
Memory Limit: 256 MB
题目连接
http://codeforces.com/contest/486/problem/D
Description
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).
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.
Sample Input
1 4
2 1 3 2
1 2
1 3
3 4
Sample Output
8
HINT
题意
给你一颗树,然后让你找到里面有多少棵子树,满足子树里面最大点减去最小点的差小于等于d
题解:
直接枚举每一个点为根,然后开始dfs,都假设这个根节点是这棵子树的最大值
然后乘法原理搞一搞就好啦
代码
#include<iostream> #include<stdio.h> #include<vector> using namespace std; #define maxn 2005 const int mod = 1e9 + 7; int a[maxn]; int d,n; vector<int> G[maxn]; long long dfs(int x,int pre,int k) { long long ans = 1; for(int i=0;i<G[x].size();i++) { int v = G[x][i]; if(v == pre || (a[k] == a[v]&&v > k))continue; if(a[k]>=a[v]&&a[k]-a[v]<=d) { ans *= ( dfs(v,x,k) + 1 ); while(ans>=mod)ans%=mod; } } return ans; } int main() { scanf("%d%d",&d,&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); for(int i=1;i<n;i++) { int u,v;scanf("%d%d",&u,&v); G[u].push_back(v); G[v].push_back(u); } long long ans = 0; for(int i=1;i<=n;i++) { ans += dfs(i,-1,i); while(ans>=mod)ans%=mod; } printf("%lld ",ans); }