You are given a rootedrooted tree of NN nodes, labeled from 1 to NN . To the ii th node a non-negative value aiai is assigned.An orderedordered pair of nodes (u,v)(u,v) is said to be weakweak if
(1) uu is an ancestor of vv (Note: In this problem a node uu is not considered an ancestor of itself);
(2) au×av≤kau×av≤k .
Can you find the number of weak pairs in the tree?
Input
There are multiple cases in the data set.
The first line of input contains an integer TT denoting number of test cases.
For each case, the first line contains two space-separated integers, NN and kk , respectively.
The second line contains NN space-separated integers, denoting a1a1 to aNaN .
Each of the subsequent lines contains two space-separated integers defining an edge connecting nodes uu and vv , where node uu is the parent of node vv .
Constrains:
1≤N≤1051≤N≤105
0≤ai≤1090≤ai≤109
0≤k≤10180≤k≤1018
Output
For each test case, print a single integer on a single line denoting the number of weak pairs in the tree.
这题一开始不会,看了题解之后敲完后wa到自闭,最后才发现是树状数组的大小应该为离散化完后的个数。。。
至于详细题解看大佬博客。。。
https://blog.csdn.net/queuelovestack/article/details/52505856
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <queue>
#define LL long long
using namespace std;
const int MAX = 2e6 + 50;
int n;
LL m;
int c[MAX];
LL a[MAX];
LL lsh[MAX];
int cnt = 0;
LL INF = 1e18 + 250;
int vis[MAX];
int lowbit(int x){
return x & (-x);
}
int head[MAX];
struct Edge
{
int to;
int next;
} edge[MAX];
int ek = 0;
void add(int a, int b){
edge[ek].to = b;
edge[ek].next = head[a];
head[a] = ek++;
}
void Update(int i, int k){
while(i <= cnt){ //!!!!!!!!!!!!!重点,树状数组的大小是离散化完后的数量
c[i] += k;
i += lowbit(i);
}
}
int getsum(int i){
int res = 0;
while(i > 0){
res += c[i];
i -= lowbit(i);
}
return res;
}
LL ans = 0;
void dfs(int rt){
LL num;
if(a[rt] == 0){
num = INF;
} else{
num = m / a[rt];
}
int x = lower_bound(lsh + 1, lsh + cnt + 1, a[rt]) - lsh;
int x1 = lower_bound(lsh + 1, lsh + cnt + 1, num) - lsh;
ans += getsum(x1);
Update(x, 1);
for(int i = head[rt]; i != -1; i = edge[i].next){
dfs(edge[i].to);
}
Update(x, -1);
}
int main(int argc, char const *argv[])
{
int t;
scanf("%d", &t);
while(t--){
ans = 0;
cnt = 0;
ek = 0;
scanf("%d%I64d", &n, &m);
for(int i = 1; i <= n; i++){
head[i] = -1;
vis[i] = 0;
}
for(int i = 1; i <= n; i++){
scanf("%I64d", &a[i]);
lsh[++cnt] = a[i];
if(a[i]){
lsh[++cnt] = m / a[i];
} else{
lsh[++cnt] = INF;
}
}
sort(lsh + 1, lsh + cnt + 1);
cnt = unique(lsh + 1, lsh + cnt + 1) - lsh - 1;
for(int i = 0; i < n - 1; i++){
int u, v;
scanf("%d%d", &u, &v);
add(u, v);
vis[v] = 1;
}
for(int i = 1; i <= n; i++){
if(!vis[i]){
dfs(i);
}
}
printf("%I64d\n", ans);
}
return 0;
}