D. Valid sets
As you know, an undirected connected graph with n nodes and n -1 edges is called a tree. You is given an integer d and a tree consisting of n nodes. Each node i have a value ai associated with it.
We call a set S of tree nodes valid if following conditions is satisfied:
- S is non-empty.
- S is connected. In other words, if nodes u and v is in S, then all nodes lying on the simple pat h between u and v should also is presented in S.
- .
Your task is to count the number of valid sets. The Since the result can be very large, and you must the print its remainder modulo 1000000007 (9 + 7).
Input
The first line contains 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 are an edge between u and v. It's guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Sample Test (s)
input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Note
In the first sample, there is 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.
Test Instructions : give you a tree of n points, and weights for each point, ask you how many seed trees meet (maximum weight point-minimum weight point) <=d
Solution: Define DP[I] to indicate the number of subtree schemes with the minimum weight of the root node, keeping this condition in mind
So the answer is ∑dp[i]%mod (1<=i<=n);
///1085422276#include <bits/stdc++.h>using namespacestd; typedefLong Longll;#defineMem (a) memset (A,0,sizeof (a))#definePB Push_back#defineMeminf (a) memset (A,127,sizeof (a));inline ll read () {ll x=0, f=1;CharCh=GetChar (); while(ch<'0'|| Ch>'9'){ if(ch=='-') f=-1; ch=GetChar (); } while(ch>='0'&&ch<='9') {x=x*Ten+ch-'0'; ch=GetChar (); }returnx*F;}//****************************************#defineMAXN 2000+50#defineMoD 1000000007#defineINF 1000000007intD,n,a[maxn],vis[maxn];vector<int>G[maxn];ll DP[MAXN];//number of scenarios with minimum root node as IvoidDfsintXintpre) {Dp[x]=1; vis[x]=1; for(intI=0; I<g[x].size (); i++){ if(!Vis[g[x][i]]) { if(a[g[x][i]]<a[pre]| | A[G[X][I]]>A[PRE]+D)Continue; if(A[g[x][i]]==a[pre]&&g[x][i]<pre)Continue; DFS (G[X][I],PRE); DP[X]= (dp[x]* (dp[g[x][i]]+1))%MoD; } }}intMain () {D=read (), n=read (); for(intI=1; i<=n;i++) {scanf ("%d",&A[i]); }intu,v; for(intI=1; i<n;i++) {scanf ("%d%d",&u,&v); G[U].PB (v); G[V].PB (U); }ll ans=0; for(intI=1; i<=n;i++) {mem (DP); mem (VIS); DFS (i,i); Ans= (Ans+dp[i])%MoD; } cout<<ans<<Endl; return 0;}
Code
Codeforces Round #277 (Div. 2) D. Valid Sets DP