跳到正文

题解

QOJ4420 Range Reachability Query 题解

sleepy66约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年9月12日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

看到 DAG 可达性问题和这个数据范围就知道肯定只能是 n2ω\frac{n ^ 2}{\omega}。

直接处理可达点比较难转移,考虑记录一个点 xx 能否从第 ii 个询问的起点 uu 出发,只经过 [l,r][l, r] 的边达到。

用 bitset fuf_u 记下上面的东西。然后再记一个 bitset e(u,v)e_{(u, v)} 表示 u→vu \to v 这条边在第 ii 这个询问中能否走。

那么转移就是 fu∣=(fv & cnt(u,v))f_{u} |= (f_{v} \ \& \ cnt_{(u, v)})。

考虑现在复杂度瓶颈是预处理 e(u,v)e_{(u, v)}。

直接在线维护 e(u,v)e_{(u, v)} 不好做,考虑离线下来。扫描线询问,在 ll 处把询问加入,在 r+1r + 1 处删除。统一放进一个 bitset 里面,每一次直接复制到 e(u,v)e_{(u, v)} 即可。

时间复杂度 O(n2ω)\mathcal O(\frac{n ^ 2}{\omega})。但是空间被卡了。

我们发现不一定要把所有询问一起处理。其实分开处理也可以。每 BB 个询问处理一次,那么复杂度为 O(n2ω)\mathcal O(\frac{n^2} {\omega}),空间降为 O(nBω)\mathcal O(\frac{nB}{\omega})。

实测 B=512B = 512 是能过的。理论上只要 B≥64B \ge 64 都能过。

C++
#include <bits/stdc++.h>
#define pii pair<int, int>
#define fi first
#define se second
using namespace std;
const int N = 50003, B = 512;
int t, n, u, v, dd[N], d[N], m, qy, x[N], y[N], l, r, tot;
queue<int> q;
bitset<B> ck, can[N << 1], f[N];
vector<pii> g[N];
vector<int> cl[N << 1], cr[N << 1];
void topo() {
	for (int i = 1; i <= n; i++) {
		d[i] = dd[i];
		if (!d[i]) q.push(i);
	}
	for (int u; !q.empty(); ) {
		u = q.front();
		q.pop();
		for (pii e : g[u]) {
			int v = e.fi, id = e.se;
			f[v] |= (f[u] & can[id]);
			d[v]--;
			if (!d[v]) q.push(v);
		}
	}
}
void clear() {
	for (int i = 1; i <= m + 1; i++) {
		cl[i].clear(), cr[i].clear();
	}
	for (int i = 1; i <= n; i++) {
		f[i] = 0;
	}
	ck = 0;
	tot = 0;
}
void solve() {
	cin >> n >> m >> qy;
	for (int i = 1; i <= n; i++) {
		g[i].clear();
		dd[i] = 0;
	}
	for (int i = 1; i <= m; i++) {
		cin >> u >> v;
		g[u].push_back({v, i});
		dd[v]++;
	}
	tot = 0;
	for (int tq = 1; tq <= qy; tq++) {
		cin >> x[tot] >> y[tot] >> l >> r;
		cl[l].push_back(tot);
		cr[r + 1].push_back(tot);
		tot++;
		if (tq == qy or tot == B) {
			for (int i = 1; i <= m; i++) {
				for (int j : cl[i]) ck[j] = 1;
				for (int j : cr[i]) ck[j] = 0;
				can[i] = ck;
			}
			for (int i = 0; i < tot; i++) {
				f[x[i]][i] = 1;
			}
			topo();
			for (int i = 0; i < tot; i++) {
				if (f[y[i]][i]) cout << "YES\n";
				else cout << "NO\n";
			}
			clear();
		}
	}

}
int main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	cin >> t;
	while (t--) solve();
}
原文