題目鏈接
http://acm.split.hdu.edu.cn/showproblem.php?pid=5877
Problem Description You are given a rooted tree of N nodes, labeled from 1 to N. To the ith node a non-negative value ai is assigned.An ordered pair of nodes (u,v) is said to be weak if
#include <iostream> #include <algorithm> #include <cstring> #include <cstdio> #include <vector> #include <map> using namespace std; const long long maxn=200003; long long root; long long sum,k; long long in[100005]; vector<long long>g[100005]; long long a[100005]; long long b[200005]; long long c[200005]; map<long long,long long>q; long long Lowbit(long long t) { return t&(t^(t-1)); } void add(long long x,long long t) { while(x > 0) { c[x]+=t; x -= Lowbit(x); } } long long Sum(long long li) { long long s=0; while(li<200005) { s+=c[li]; li=li+Lowbit(li); } return s; } void dfs(long long t) { long long n=g[t].size(); for(long long i=0;i<n;i++) { long long v=g[t][i]; sum+=(long long)Sum(q[a[v]]); if(a[v]==0) add(maxn,1); else add(q[k/a[v]],1); dfs(v); if(a[v]==0) add(maxn,-1); else add(q[k/a[v]],-1); } } int main() { long long T,N; scanf("%lld",&T); while(T--) { q.clear(); memset(in,0,sizeof(in)); memset(c,0,sizeof(c)); memset(b,0,sizeof(b)); scanf("%lld%lld",&N,&k); for(long long i=1;i<=N;i++) { scanf("%lld",&a[i]); b[2*i-2]=a[i]; if(a[i]!=0) b[2*i-1]=k/a[i]; g[i].clear(); } sort(b,b+2*N); long long tot=0,pre=-1; for(long long i=0;i<2*N;i++) { if(b[i]!=pre) { pre=b[i]; q[pre]=++tot; } } for(long long i=0;i<N-1;i++) { long long aa,bb; scanf("%lld%lld",&aa,&bb); g[aa].push_back(bb); in[bb]++; } for(long long i=1;i<=N;i++) if(in[i]==0) { root=i; break; } sum=0; if(a[root]==0) add(maxn,1); else add(q[k/a[root]],1); dfs(root); printf("%lld\n",sum); } return 0; }