思路来源于某个大佬,昨天看的,今天找不到那篇了。。。就不附链接了。。。
题意:给你一棵树,每个结点都有一个值a[i],询问你有没有这样的成对结点(u,v),使得:
1、u是v的父结点(或父结点的父结点或父节点的父结点的父结点……),且u!=v。
2、u的值与v的值相乘小于等于题目所给的k(即a[u]*a[v]<=k)。
思路:看完题意,相信大家和我一样,一头雾水,二脸懵逼,无从下手。但是我们总是从题目特点入手的嘛:
1、首先转化一下a[u]*a[v]<=k的形式,其等价于a[u]<=k/a[v]。意思是,用当前结点的k/a[v]值与父结点们的a[u]作比较,满足a[u]<=k/a[v]的就计入答案。这样是不是一个前缀和的形式?所以我们可以用树状数组来计算之前有多少个父结点符合条件,即:即统计当前结点v的所有父节点 u,有多少个父结点的a[u]小于当前结点的k/a[v]。
2、限制条件是u是v的父结点,所以我们想到搜索,因为若从根节点开始搜,如果你想搜到一个子结点,那么一定会先搜到他的父结点。所以核心思路是:每当搜索到一个结点,就看看这个结点之前有多少父结点满足条件。
3、数据范围很大(1e9),而总量不大(1e5),所以为了防止MLE和TLE,要采用离散化。
4、为了防止兄弟结点的影响(即,若之前搜过当前结点的兄弟结点,那么兄弟结点肯定加入过你用来统计的树状数组,所以每当搜索完一个结点时,需要把这个结点从你的树状数组中去掉。(保证每个结点找符合要求的父结点的时候,树状数组里保存的都是父结点的信息而不包含兄弟结点的信息)。
下面是AC代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define ll long long
#define inf 0x3f3f3f3f
#define cl(a,b) memset(a,b,sizeof(a))
#define lowbit(i) (i&(-i))
using namespace std;
const int maxn=1e5+5;
int n,cnt,size;//点数 边数 去重后边数
int a[maxn],b[maxn],c[maxn],head[maxn],in[maxn];
ll k,ans;//ans最终答案
struct node{
int v,next;
}side[maxn];
void init(){
cnt=0,ans=0;
for(int i=1;i<=n;i++){
c[i]=0;
head[i]=-1;
in[i]=0;
}
}
void add(int u,int v){
cnt++;
side[cnt].v=v;
side[cnt].next=head[u];
head[u]=cnt;
}
void updata(int i,int val){
while(i<=n){
c[i]+=val;
i+=lowbit(i);
}
}
ll sum(int i){
ll ans=0;
while(i>0){
ans+=c[i];
i-=lowbit(i);
}
return ans;
}
void dfs(int u){
int x=upper_bound(b+1,b+size+1,k/a[u])-b-1;
ans+=sum(x);
int y=lower_bound(b+1,b+size+1,a[u])-b;
updata(y,1);
for(int i=head[u];i!=-1;i=side[i].next){
int v=side[i].v;
dfs(v);
}
updata(y,-1);
}
int main(){
int T;
cin>>T;
while(T--){
scanf("%d%lld",&n,&k);
init();
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
b[i]=a[i];
}
for(int i=1;i<n;i++){
int u,v;
scanf("%d%d",&u,&v);
add(u,v);
in[v]++;//统计入度
}
sort(b+1,b+cnt+1);
size=unique(b+1,b+cnt+1)-(b+1);
for(int i=1;i<=n;i++){
if(in[i]==0){
dfs(i);
break;
}
}
printf("%lld\n",ans);
}
return 0;
}
题目:
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? InputThere 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
OutputFor each test case, print a single integer on a single line denoting the number of weak pairs in the tree.Sample Input1
2 3
1 2
1 2Sample Output1