树形DP+树状数组 HDU 5877 Weak Pair

时间:2023-03-08 22:07:35
 //树形DP+树状数组 HDU 5877  Weak Pair
// 思路:用树状数组每次加k/a[i],每个节点ans+=Sum(a[i]) 表示每次加大于等于a[i]的值
// 这道题要离散化 #include <bits/stdc++.h>
using namespace std;
#define LL long long
typedef pair<int,int> pii;
const double inf = 123456789012345.0;
const LL MOD =100000000LL;
const int N = 2e5+;
const int maxx = ;
#define clc(a,b) memset(a,b,sizeof(a))
const double eps = 1e-;
void fre() {freopen("in.txt","r",stdin);}
void freout() {freopen("out.txt","w",stdout);}
inline int read() {int x=,f=;char ch=getchar();while(ch>''||ch<'') {if(ch=='-') f=-; ch=getchar();}while(ch>=''&&ch<='') {x=x*+ch-'';ch=getchar();}return x*f;} map<LL,LL> ma;
LL a[N];
LL c[N],b[N];
LL in[N];
vector<LL> g[N];
LL lowbit(LL x){ return x&(-x);}
LL add(LL x,int t){
while(x>){
c[x]+=t;
x-=lowbit(x);
}
}
LL Sum(LL x){
LL sum=;
while(x<maxx){
sum+=c[x];
x+=lowbit(x);
}
return sum;
} LL ans=;
LL n,k;
void dfs(LL rt){
for(LL i=;i<(int)g[rt].size();i++){
LL v=g[rt][i];
ans+=Sum(ma[a[v]]);
if(a[v]==) add(maxx,);
else add(ma[k/a[v]],);
dfs(v);
if(a[v]==) add(maxx,-);
else add(ma[k/a[v]],-);
}
}
int main(){
int T;
scanf("%d",&T);
while(T--){
ma.clear();
memset(c,,sizeof(c));
scanf("%I64d%I64d",&n,&k);
for(int i=;i<=n;i++){
scanf("%I64d",&a[i]);
b[i*-]=a[i];
if(a[i]!=) b[i*-]=k/a[i];
g[i].clear();
in[i]=;
}
sort(b,b+*n);
int K=unique(b,b+*n)-b;
int cxt=;
for(int i=;i<K;i++){
ma[b[i]]=++cxt;
}
for(LL i=;i<n-;i++){
LL u,v;
scanf("%I64d%I64d",&u,&v);
g[u].push_back(v);
in[v]++;
}
LL rt;
for(LL i=;i<=n;i++){
if(in[i]==){
rt=i;
break;
}
}
ans=;
if(a[rt]==) add(maxx,);
else add(ma[k/a[rt]],);
dfs(rt);
printf("%I64d\n",ans);
}
return ;
}