其他分享
首页 > 其他分享> > CodeForces 1662F Antennas

CodeForces 1662F Antennas

作者:互联网

洛谷传送门

CF 传送门

思路

边权为 \(1\) 的最短路问题,可使用 BFS 求解。当目前搜到点 \(u\) 时,瓶颈在于找出所有边 \(u \to v\),若 \(v\) 没被访问过就入队。

下面的部分和 [JOISC2020] 治療計画 有点像。考虑先拆限制中的绝对值。

由于每个点只会入队一次,所以时间复杂度有保证,为 \(O(n \log n)\)。

代码

code
/*

p_b_p_b txdy
AThousandMoon txdy
AThousandSuns txdy
hxy txdy

*/

#include <bits/stdc++.h>
#define pb push_back
#define fst first
#define scd second

using namespace std;
typedef long long ll;
typedef pair<ll, ll> pii;

const int maxn = 200100;
const int inf = 0x3f3f3f3f;

int n, S, T, a[maxn], f[maxn], L[maxn], R[maxn];
queue<int> q;

struct node {
	int mx, mn;
} tree[maxn << 2];

void pushup(int x) {
	tree[x].mx = max(tree[x << 1].mx, tree[x << 1 | 1].mx);
	tree[x].mn = min(tree[x << 1].mn, tree[x << 1 | 1].mn);
}

void build(int rt, int l, int r) {
	if (l == r) {
		if (l == S) {
			tree[rt].mx = -inf;
			tree[rt].mn = inf;
		} else {
			tree[rt].mx = R[l];
			tree[rt].mn = L[l];
		}
		return;
	}
	int mid = (l + r) >> 1;
	build(rt << 1, l, mid);
	build(rt << 1 | 1, mid + 1, r);
	pushup(rt);
}

void update1(int rt, int l, int r, int ql, int qr, int x) {
	if (ql > qr) {
		return;
	}
	if (tree[rt].mn > x) {
		return;
	}
	if (l == r) {
		f[l] = f[x] + 1;
		tree[rt].mn = inf;
		tree[rt].mx = -inf;
		q.push(l);
		return;
	}
	int mid = (l + r) >> 1;
	if (ql <= mid) {
		update1(rt << 1, l, mid, ql, qr, x);
	}
	if (qr > mid) {
		update1(rt << 1 | 1, mid + 1, r, ql, qr, x);
	}
	pushup(rt);
}

void update2(int rt, int l, int r, int ql, int qr, int x) {
	if (ql > qr) {
		return;
	}
	if (tree[rt].mx < x) {
		return;
	}
	if (l == r) {
		f[l] = f[x] + 1;
		tree[rt].mn = inf;
		tree[rt].mx = -inf;
		q.push(l);
		return;
	}
	int mid = (l + r) >> 1;
	if (ql <= mid) {
		update2(rt << 1, l, mid, ql, qr, x);
	}
	if (qr > mid) {
		update2(rt << 1 | 1, mid + 1, r, ql, qr, x);
	}
	pushup(rt);
}

void solve() {
	scanf("%d%d%d", &n, &S, &T);
	for (int i = 1; i <= n; ++i) {
		scanf("%d", &a[i]);
		L[i] = max(1, i - a[i]);
		R[i] = min(n, i + a[i]);
		f[i] = 0;
	}
	build(1, 1, n);
	while (q.size()) {
		q.pop();
	}
	q.push(S);
	while (q.size()) {
		int u = q.front();
		q.pop();
		update1(1, 1, n, u + 1, R[u], u);
		update2(1, 1, n, L[u], u - 1, u);
	}
	printf("%d\n", f[T]);
}

int main() {
	int T = 1;
	scanf("%d", &T);
	while (T--) {
		solve();
	}
	return 0;
}

标签:rt,le,return,1662F,tree,CodeForces,int,maxn,Antennas
来源: https://www.cnblogs.com/zltzlt-blog/p/16476369.html