询问最大值与最小值之差为k好像比较困难,所以可以把转换成求最大值与最小值之差小于等于k的问题,等于k的数量=小于等于k的数量-小于等于k-1的数量
这样可以在树上进行DFS,时间复杂度O(n^2)
#include<cstdio> using namespace std; typedef long long ll; const ll mod=19260817; int head[3335],len,n,k,x,y; ll val[3335],ans; struct EDGE{ int to,next; }edge[7005]; void add(int x,int y){ ++len; edge[len].to=y; edge[len].next=head[x]; head[x]=len; } ll dfs(int u,int fa,int root,int k){ ll mul=1; for (register int i=head[u];i;i=edge[i].next){ int v=edge[i].to; if (v!=fa&&val[root]>=val[v]&&(val[root]!=val[v]||root<v)&&val[root]-val[v]<=k){ mul=1ll*mul*(dfs(v,u,root,k)+1); mul%=mod; } } return mul; } int main(){ scanf ("%d%d",&n,&k); for (register int i=1;i<=n;++i) scanf ("%d",&val[i]); for (register int i=1;i<n;++i){ scanf ("%d%d",&x,&y); add(x,y);add(y,x); } for (register int i=1;i<=n;++i){ if (k==0) ans=(ans+dfs(i,0,i,k))%mod; else ans=(ans+dfs(i,0,i,k)-dfs(i,0,i,k-1)+mod)%mod; } printf ("%lld\n",ans); return 0; }