ABC F 求调
  • 板块学术版
  • 楼主Xy_top
  • 当前回复3
  • 已保存回复3
  • 发布时间2024/8/3 21:41
  • 上次更新2024/8/3 23:05:47
查看原帖
ABC F 求调
637796
Xy_top楼主2024/8/3 21:41

rtrt,线段树。

#include<bits/stdc++.h>
#define For(i, a, b) for(int i = (a); i <= (b); i ++)
#define foR(i, a, b) for(int i = (a); i >= (b); i --)
#define int long long
using namespace std;
int n, q;
int x[200005], y[200005];
struct Seg {
	int sx, sy, tx, ty;
	int mi;
}a[800005];
Seg merge (Seg s1, Seg s2) {
	Seg ret;
	ret.mi = s1.mi + s2.mi + 1;
	if (min (s1.ty, s2.sy) >= max (s1.tx, s2.sx) ) {
		if (s1.tx != s1.ty) {
			ret.sx = max (s1.tx, s2.sx);
			ret.sy = min (s1.ty, s2.sy);
		} else {
			ret.sx = s1.sx;
			ret.sy = s1.sy;
		}
		if (s2.sx != s2.sy) {
			ret.tx = max (s1.tx, s2.sx);
			ret.ty = min (s1.ty, s2.sy);
		} else {
			ret.tx = s2.tx;
			ret.ty = s2.ty;
		}
	} else {
		if (s1.ty < s2.sx) {
			ret.mi += s2.sx - s1.ty;
			ret.sx = s1.sy;
			ret.sy = s1.sy;
			ret.tx = s2.tx;
			ret.ty = s2.tx;
		} else {//s1.tx > s2.sy
			ret.mi += s1.tx - s2.sy;
			ret.sx = s1.sx;
			ret.sy = s1.sx;
			ret.tx = s2.ty;
			ret.ty = s2.ty;
		}
	}
	return ret;
}
void build (int l, int r, int k) {
	if (l == r) {
		a[k] = {x[l], y[l], x[l], y[l], 0};
		return;
	}
	int mid = l + r >> 1;
	build (l, mid, k << 1);
	build (mid + 1, r, k << 1 | 1);
	a[k] = merge (a[k << 1], a[k << 1 | 1]);
}
Seg query (int l, int r, int k, int x, int y) {
	if (x <= l && y >= r) return a[k];
	int mid = l + r >> 1;
	if (y <= mid) return query (l, mid, k << 1, x, y);
	if (x > mid) return query (mid + 1, r, k << 1 | 1, x, y);
	return merge (query (l, mid, k << 1, x, y), query (mid + 1, r, k << 1 | 1, x, y) );
}
void solve () {
	cin >> n;
	For (i, 1, n) cin >> x[i] >> y[i];
	build (1, n, 1);
	cin >> q;
	while (q --) {
		int sx, sy, tx, ty;
		cin >> sx >> sy >> tx >> ty;
		if (sx > tx) swap (sx, tx);
		if (sx == tx) {
			cout << abs (sy - ty) << '\n';
			continue;
		}
		Seg s = query (1, n, 1, sx, tx);
		int ans = 10000000000000000LL;
		if (s.sx <= sy && sy <= s.sy) {
			if (s.sx == s.sy) {
				cout << abs (s.ty - ty) + s.mi << '\n';
			} else {
				cout << abs (sy - ty) + s.mi << '\n';
			}
		} else if (s.tx <= ty && ty <= s.ty) {
			if (s.tx == s.ty) {
				cout << abs (s.sx - sy) + s.mi << '\n';
			} else cout << abs (sy - ty) + s.mi << '\n';
		} else {
			if (s.tx == s.ty) cout << abs (sy - s.sx) + abs (ty - s.tx) + s.mi << '\n';
			else {
				if ( (sy < s.sx && ty > s.ty) || (sy > s.sy && ty < s.tx) ) {
					cout << s.mi + abs (sy - ty) << '\n';
				} else {
					cout << s.mi + min (abs (s.sx - sy) + abs (s.tx - ty), abs (s.sy - sy) + abs (s.ty - ty) ) << '\n';
				}
			}
		}
		
	}
}
signed main() {
	int _ = 1;
//	cin >> _;
	while (_ --) {
		solve ();
		cout << '\n';
	}
	return 0;
}
2024/8/3 21:41
加载中...