1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| #include<bits/stdc++.h> #define pb push_back using namespace std; class BITree{ public: static const int SIZE = 300010, BIAS = 5; long long u[SIZE]; void clear(){ memset(u,0,sizeof(u)); } void modify(int x, long long v){ for(x+=BIAS;x<SIZE;x+=x&-x) u[x]+=v; } long long getsum(int x){ long long s=0; for(x+=BIAS;x;x-=x&-x) s+=u[x]; return s; } } trl,trr; int n,m; int e[100010][2]; int w[100010]; int Q; vector<int> q[100010]; vector<int> id[100010]; int ans1[100010]; int ans2[100010]; vector<int> t; map<int,int> ha; void dfs(int x,int fa,int wi) { for(int i=0;i<q[x].size();i++) { int p=ha[q[x][i]]; int u=id[x][i]; int bj=trl.getsum(p)-trl.getsum(p-1)+trr.getsum(p)-trr.getsum(p-1); if(bj!=0) ans1[u]=0,ans2[u]=-1; else { ans2[u]+=trl.getsum(p)*3; ans2[u]+=(trl.getsum(200001)-trl.getsum(p)); ans2[u]+=trr.getsum(p)*3; ans2[u]+=(trr.getsum(200001)-trr.getsum(p)); ans1[u]+=trr.getsum(p); } } if(e[x][0]!=0) { trl.modify(ha[w[x]],1); dfs(e[x][0],x,0); trr.modify(ha[w[x]],1); dfs(e[x][1],x,1); } if(fa!=0) { if(wi==0) trl.modify(ha[w[fa]],-1); if(wi==1) trr.modify(ha[w[fa]],-1); } return; } void work() { ha.clear(); t.clear(); scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&w[i]); t.pb(w[i]); e[i][0]=e[i][1]=0; q[i].clear(); id[i].clear(); } scanf("%d",&m); for(int i=1;i<=m;i++) { int u,a,b; scanf("%d%d%d",&u,&a,&b); e[u][0]=a; e[u][1]=b; } scanf("%d",&Q); for(int i=1;i<=Q;i++) { ans1[i]=0; ans2[i]=0; int v,x; scanf("%d%d",&v,&x); q[v].pb(x); t.pb(x); id[v].pb(i); } sort(t.begin(),t.end()); int num=0; for(auto &i:t) { num++; ha[i]=num; } trl.clear(); trr.clear(); dfs(1,0,-1); for(int i=1;i<=Q;i++) { if(ans2[i]==-1) printf("%d\n",ans1[i]); else printf("%d %d\n",ans1[i],ans2[i]); } } int main() { int T; scanf("%d",&T); while(T--) work(); return 0; }
|