Weak Pair
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 weakif
(1) u is an ancestor of v (Note: In this problem a node u is not considered an ancestor of itself;
(2) au*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 T denoting number of test cases.
For each case, the first line contains two space-separated integers, N and k, respectively.
The second line contains N space-separated integers, denoting a1 to aN.
Each of the subsequent lines contains two space-separated integers defining an edgeconnecting nodes u and v , where node u is the parent of node v.
Constrains:
1≤N≤10^5
0≤ai≤10^9
0≤k≤10^18Output
For each test case, print a single integer on a single line denoting the number of
weak pairs in the tree.
Sample Input
2
2 3
1 2
1 25 10
1 2 0 4 5
1 2
1 3
2 5
2 4Sample Output
1
6
题意:
n个节点到有根树,u是v的祖先,每个节点有个权值a[u].
求a[u] * a[v] <= k的有序对的数量。
思路:
完全没往树状数组上想,应该是没想到dfs序和线性序列的相似
性,思路有了代码实现挺简单,注意熟练即可。
代码实现:
#include <iostream>
#include <string.h>
#include <math.h>
#include <ctime>
#include <queue>
#include <map>
#include <stdio.h>
#include <algorithm>
#define LL long long
#define INF 0x3f3f3f3f3f3f3f3f
#define ull unsigned long long
using namespace std;
const int N = 2e5 + 100;
const int M = 4e5 + 100;
const int mod = 1e9 + 7;
long long t, n , k, ans, arr[N], brr[N], tn;
int tc[N];
int head[N], Next[M], ver[M], tot;
int deg[N], root;
void add (int x, int y) {
ver[++tot] = y;
Next[tot] = head[x];
head[x] = tot;
}
int query (int x) {
int res = 0;
for (; x; x -= x&-x) res += tc[x];
return res;
}
void change (int x, int y) {
for (; x <=tn; x += x&-x) tc[x] += y;
}
void sol (int x) {
ans += query(arr[x] ?
upper_bound(brr+1, brr+1+tn, k/arr[x]) - brr - 1 : tn);
change(lower_bound(brr+1, brr+1+tn, arr[x]) - brr, 1);
for (int i = head[x]; i; i = Next[i]) sol(ver[i]);
change(lower_bound(brr+1, brr+1+tn, arr[x]) - brr, -1);
}
int main () {
#ifdef MYHOME_Wjvje
freopen("input.txt","r",stdin);
#endif
int x, y;
while (scanf("%lld", &t) != EOF) {
while (t--) {
memset(deg, 0, sizeof(deg));
tot = ans = 0;
memset(head, 0, sizeof(head));
memset(Next, 0, sizeof(Next));
memset(tc, 0, sizeof(tc));
memset(brr, 0, sizeof(brr));
scanf("%lld %lld", &n, &k);
for (int i = 1; i <= n; i ++)
scanf("%lld", &arr[i]), brr[i] = arr[i];
sort(brr+1, brr+1+n);
tn = unique(brr+1,brr+1+n) - brr - 1;
for (int i = 1; i < n; i ++)
scanf("%d %d", &x, &y), add(x, y), deg[y] ++;
for (int i = 1; i <= n; i ++)
if (deg[i] == 0) root = i;
sol(root);
printf("%lld\n", ans);
}
}
return 0;
}
THE END;