hdu5877 Weak Pair(DFS+树状数组)

思路:查询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×avk .

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: 
  
   1N105  
  
   0ai109  
  
   0k1018
 

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
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值