思路:查询a[u]*a[v]<=k的对数,那么其实就是查询a[v]>=k/a[u],那么离散一下,在DFS的时候用树状数组统计一下就可以了
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5+7;
#define LL long long
LL lowbit(LL i){return i&(-i);}
LL c[maxn],a[maxn],k,ans=0;
vector<LL>v;
vector<LL>e[maxn];
LL n,in[maxn];
LL getid(LL x){return lower_bound(v.begin(),v.end(),x)-v.begin()+1;}
void update(LL i,LL v)
{
while(i)
{
c[i]+=v;
i-=lowbit(i);
}
}
LL query(LL i)
{
LL res = 0;
while(i<=maxn)
{
res+=c[i];
i+=lowbit(i);
}
return res;
}
void dfs(LL u)
{
for(LL i = 0;i<e[u].size();i++)
{
LL v = e[u][i];
// if(v==fa)continue;
ans+=query(getid(a[v]));
// if(a[v]==0)update(maxn,1);
// else
update(getid(k/a[v]),1);
dfs(v);
//if(a[v]==0)update(maxn,-1);
//else
update(getid(k/a[v]),-1);
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%lld%lld",&n,&k);
v.clear();
for(int i = 0;i<=n;i++)
e[i].clear();
memset(in,0,sizeof(in));
ans = 0;
memset(c,0,sizeof(c));
for(int i = 1;i<=n;i++)
{
scanf("%lld",&a[i]);
// if(a[i]!=0)
v.push_back(k/a[i]);
v.push_back(a[i]);
}
sort(v.begin(),v.end());
v.erase(unique(v.begin(),v.end()),v.end());
for(int i = 1;i<=n-1;i++)
{
LL u,v;
scanf("%lld%lld",&u,&v);
e[u].push_back(v);
in[v]++;
}
LL root = 0;
for(int i = 1;i<=n;i++)
if(!in[i])
{
root = i;
break;
}
// if(a[root]==0)
// update(maxn,1);
// else
update(getid(k/a[root]),1);
dfs(root);
printf("%lld\n",ans);
}
}
Problem Description
You are given a
rooted
tree of
N
nodes, labeled from 1 to
N
. To the
i
th node a non-negative value
ai
is assigned.An
ordered
pair of nodes
(u,v)
is said to be
weak
if
(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?
(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 edge connecting nodes u and v , where node u is the parent of node v .
Constrains:
1≤N≤105
0≤ai≤109
0≤k≤1018
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 edge connecting nodes u and v , where node u is the parent of node v .
Constrains:
1≤N≤105
0≤ai≤109
0≤k≤1018
Output
For each test case, print a single integer on a single line denoting the number of weak pairs in the tree.
Sample Input
1 2 3 1 2 1 2
Sample Output
1
Source