力大堆飞 P3261(五)
书接上文。路径对折。
一个废物。记下来是因为它成立。
我们注意到所有
于是我们考虑从每个点向上预处理若干个长度为 2 的幂的路径区间。设该点深度为
从这个点向上长度为不超过这个数的所有 2 的幂的路径区间将被预处理。那么我们可以证明两个事情:所有点的区间总长线性于节点总数
先来处理第一个结论。我们考虑一个动态加叶子的过程。除了叶子
-
该节点
x 为p 的祖先; -
-
设
p 的深度为d_p ,x 的深度为d_x ,则d_p\in(d_x+\lfloor\log_2(d_x)\rfloor-\operatorname{popcnt}(d_x)-\operatorname{ctz}(d_x),d_x+\lfloor\log_2(d_x)\rfloor-\operatorname{popcnt}(d_x)]] 。
由于
再来处理第二个结论。我们采用如下策略刻画一条从一个点到其祖先的路径:从当前点开始,每步转移到最浅的、在这条路径上的、该节点的某个路径区间的祖先。我们把这个过程分为两个阶段:
- 子树高度小于
\lfloor\log_2(n)\rfloor
这一阶段显然只会跳不超过
- 子树高度不小于
\lfloor\log_2(n)\rfloor
此时深度为
于是它的复杂度是对的。代码还算好写,但是太魔怔。
#include <bits/stdc++.h>
#define int long long
using namespace std;
constexpr int N = 3e5 + 9, A = 1e18;
int n, m, fa[N], d[N], rk[N], ans[N], cnt[N], len[N];
vector<int> es[N];
struct func {
int xl, xr, yl, yr;
int getk() const { return xl == xr ? 1 : (yr - yl) / (xr - xl); }
int operator()(int x) const { return (x - xl) * getk() + yl; }
friend func operator+(const func& a, const func& b) {
static auto mnov = [](int x, int y) { return x < 0 ? 0 : (x + y - 1) / y; };
if (a.xl > a.xr) return a;
if (b.xl > b.xr) return b;
int k = a.getk();
func c;
c.xl = mnov(b.xl - a.yl, k) + a.xl;
c.xr = a.xr - mnov(a.yr - b.xr, k);
if (c.xl > c.xr) return {1, 0, 0, 0};
c.yl = b(a(c.xl)), c.yr = b(a(c.xr));
return c;
}
func& operator+=(const func& to) { return *this = *this + to; }
} vl[N];
vector<func> tr[N];
vector<int> fth[N];
int dfs1(int x) {
int p = d[x] = d[fa[x]] + 1, ret = 0;
for (int y : es[x]) fa[y] = x, ret = max(ret, dfs1(y));
len[x] =
max(__builtin_ctz(p) -
max(__builtin_ia32_bsrsi(p) - __builtin_popcount(p) - ret, 0ll),
0ll);
return ret + 1;
}
void dfs2(int x) {
int m = len[x];
fth[x].resize(m + 1), tr[x].resize(m + 1, {1, 0, 0, 0});
int f = fth[x][0] = fa[x];
func g = tr[x][0] = vl[x];
for (int j = 0; j < m && f; ++j)
tr[x][j + 1] = g += tr[f][j], fth[x][j + 1] = f = fth[f][j];
for (int y : es[x]) dfs2(y);
}
void init() {
int h[N];
for (int i = 1; i <= n; ++i) cin >> h[i];
vl[1] = {h[1], A, h[1], A};
for (int i = 2, a, v; i <= n; ++i) {
cin >> fa[i] >> a >> v;
if (es[fa[i]].push_back(i); !a) {
int xl = max(-A - min(v, 0ll), h[i]), xr = A - max(v, 0ll);
vl[i] = {xl, xr, xl + v, xr + v};
} else {
int xl = h[i], xr = A / v;
vl[i] = {xl, xr, xl * v, xr * v};
}
}
}
int calc(int x, int h) {
while (x) {
if (func f = tr[x].back(); h >= f.xl && h <= f.xr) {
h = f(h), x = fth[x].back();
continue;
}
for (int i = len[x] - 1; ~i && x; --i)
if (func f = tr[x][i]; h >= f.xl && h <= f.xr) h = f(h), x = fth[x][i];
break;
}
return x;
}
signed main() {
cin.tie(nullptr)->sync_with_stdio(false);
cin >> n >> m, init(), dfs1(1), dfs2(1);
for (int i = 1, s, c; i <= m; ++i) {
cin >> s >> c;
int x = calc(c, s);
++cnt[x], ans[i] = d[c] - d[x];
}
for (int i = 1; i <= n; ++i) cout << cnt[i] << '\n';
for (int i = 1; i <= m; ++i) cout << ans[i] << '\n';
return cout << flush, 0;
}
__builtin_popcount 在现代硬件上可以视为
魔怔的背后,有老哥能看出这东西的心路与来源吗(
其实是把某个挺典的东西包装了一下,然后就变得非常奇异搞笑!!1