Weak Pair
Time limit:4000/2000 MS (java/others) Memory limit:262144/262144 K (java/others)
Total submission (s): 333 Accepted Submission (s): 111
Problem Descriptionyou is given arooted Tree ofNNodes, labeled from 1 toN. to theITH Node A non-negative valueai is assigned. AnoRdEred Pair of nodes(u,v) is saidWeak If
(1)uis an ancestor ofv(Note:in This problem a nodeu is not considered an ancestor of itself);
(2) auxav≤k.
Can you find The number of weak pairs in the tree?
Inputthere is multiple cases in the data set.
The first line of input contains an integerTDenoting number of test cases.
For each case, the first line contains the space-separated integers,Nandk, respectively.
The second line containsNspace-separated integers, denotinga1 ToaN .
Each of the subsequent lines contains, space-separated integers defining an edge connecting nodesuandv, where nodeuis the parent of nodev.
Constrains:
1≤N≤5
0≤ai≤9
0≤k≤
Outputfor each test case, print a single integer on a denoting the number of weak pairs in the tree.
Sample Input12 31 21 2
Sample OUTPUT1Analysis: dfs+ tree-like array + discretization;Code:
#include <iostream>#include<cstdio>#include<cstdlib>#include<cmath>#include<algorithm>#include<climits>#include<cstring>#include<string>#include<Set>#include<map>#include<queue>#include<stack>#include<vector>#include<list>#defineRep (I,m,n) for (i=m;i<=n;i++)#defineRSP (It,s) for (Set<int>::iterator It=s.begin (); It!=s.end (); it++)#defineMoD 1000000007#defineINF 0x3f3f3f3f#defineVI vector<int>#definePB Push_back#defineMP Make_pair#defineFi first#defineSe Second#definell Long Long#definePi ACOs (-1.0)#definePII pair<int,int>#defineLson L, Mid, rt<<1#defineRson mid+1, R, rt<<1|1Const intmaxn=2e5+Ten;using namespacestd;ll gcd (ll p,ll q) {returnq==0? P:GCD (q,p%q);} ll Qpow (ll p,ll q) {ll F=1; while(q) {if(q&1) f=f*p;p=p*p;q>>=1;}returnF;}intN,m,k,t,h[maxn],tot,q[maxn],fa[maxn],num;ll ANS,A[MAXN],B[MAXN],C[MAXN];structnode{intTO,NXT;} E[MAXN];voidAddintXinty) {Tot++; E[tot].to=y; E[TOT].NXT=H[x]; H[X]=tot;}voidGaointXinty) { for(inti=x;i<=num+5; i+= (i& (-i))) Q[i]+=y;}int Get(intx) { intret=0; for(inti=x;i;i-= (i& (-i)) ret+=Q[i]; returnret;}voidDfsintNow ) {ans+=Get(num+5)-Get(a[now]-1); Gao (b[now),1); for(intI=h[now];i;i=e[i].nxt) {DFS (e[i].to); } Gao (B[now],-1);}intMain () {inti,j; scanf ("%d",&t); while(t--) {ans=0; Tot=0; J=0; ll P; memset (H,0,sizeofh); memset (FA,0,sizeofFA); memset (q,0,sizeofq); scanf ("%d%lld",&n,&p); Rep (I,1, N) {scanf ("%lld",&A[i]); if(a[i]==0) b[i]=1e19; Elseb[i]=p/A[i]; C[j++]=a[i],c[j++]=B[i]; } sort (C,c+j); Num=unique (C,C+J)-C; Rep (I,1, N) a[i]=lower_bound (C,c+num,a[i])-c+2, B[i]=lower_bound (C,c+num,b[i])-c+2; Rep (I,1, N-1) { intx, y; scanf ("%d%d",&x,&y); Add (x, y); Fa[y]=x; } Rep (I,1, N)if(!Fa[i]) DFS (i); printf ("%lld\n", ans); } //System ("Pause"); return 0;}
2016 Dalian Network race Weak Pair