题目链接
做过类似的题,是求区间内不超过k的最大值。这个题是做一个dfs序。在区间[l,r]找不超过k/val[l]的值。不过因为%lld读入写成了%d的问题,wa了近3个小时,10+发。菜到想抽自己。
下面是ac代码:
#include <iostream>
#include <string>
#include <cstring>
#include <queue>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#define ll long long
using namespace std;
const int N = 200005;
int c[N];
int he[N], ver[N], ne[N];
int l[N], r[N];
int tot, cnt;
bool di[N];
struct qy
{
int l, r;
ll h;
int ind;
}qu[N];
struct po
{
int ind;
ll h;
}su[N];
void init()
{
memset(he, 0, sizeof(he));
memset(di, 0, sizeof(di));
tot = 1;
cnt = 0;
}
void add_e(int x, int y)
{
ver[++tot] = y;
ne[tot] = he[x];
he[x] = tot;
}
void dfs(int x, int fa)
{
cnt++;
l[x] = cnt;
for (int i = he[x]; i; i = ne[i])
{
int y = ver[i];
if (y == fa) continue;
dfs(y, x);
}
r[x] = cnt;
}
int n;
ll m;
bool cmp(qy a, qy b)
{
return a.h < b.h;
}
bool cmp1(po a, po b)
{
return a.h < b.h;
}
void add(int x, int y)
{
for (;x <= N-2; x += x & -x) c[x] += y;
}
int ask(int x)
{
int ans = 0;
for (; x; x -= x &-x) ans += c[x];
return ans;
}
int main()
{
int t;
int t0 = 1;
cin >> t;
while(t--)
{
init();
scanf("%d%lld", &n, &m);
for (int i = 1; i <= n; i++)
{
scanf("%lld", &su[i].h);
}
for (int i =1; i < n; i++)
{
int x, y;
scanf("%d%d", &x, &y);
add_e(x, y);
add_e(y, x);
di[y] = 1;
}
for (int i = 1; i <= n; i++)
if (!di[i])
{
dfs(i, 0);
break;
}
for (int i = 1; i <= n; i++)
{
su[i].ind = l[i];
}
int ans0 = 0;
// for (int i = 1; i <= n; i++)
// cout << l[i] <<" " << r[i] << endl;
for (int i = 1; i <= n; i++)
{
qu[i].l = l[i];
qu[i].r = r[i];
if (su[i].h == 0)
qu[i].h = 10000000066ll;
else
qu[i].h = m / su[i].h;
if (su[i].h <= qu[i].h) ans0++;
}
sort(su+1, su + n + 1, cmp1);
sort(qu+1, qu + n + 1, cmp);
memset(c, 0, sizeof(c));
// for (int i = 1; i <= n; i++)
// {
// cout << qu[i].l <<" " << qu[i].r << " " <<qu[i].h << endl;
// }
int j = 1;
int ans = 0;
for (int i = 1; i <= n; i++)
{
while(su[j].h <= qu[i].h && j <= n)
{
add(su[j].ind, 1);
j++;
}
// cout << ask(qu[i].r) - ask(qu[i].l-1) << endl;
ans += ask(qu[i].r) - ask(qu[i].l-1);
}
printf("%d\n", ans - ans0);
}
return 0;
}
//%lld卡了3小时海行