#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<utility>
#include<functional>
using namespace std;
const int maxn = 151111;
const int INF = 2147483647;
typedef long long LL;
typedef pair<int, int> pii;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
struct SegTree {
int A[maxn << 2], B[maxn << 2];
inline void build(int l, int r, int rt) {
A[rt] = B[rt] = INF;
if (l == r)
return;
int m = (l + r) >> 1;
build(lson);
build(rson);
}
inline void pushup(int rt) {
A[rt] = min(A[rt << 1], A[rt << 1 | 1]);
B[rt] = min(B[rt << 1], B[rt << 1 | 1]);
}
void update(int p, int v1, int v2, int l, int r, int rt) {
if (l == r) {
A[rt] = v1;
B[rt] = v2;
return;
}
int m = (l + r) >> 1;
if (p <= m)
update(p, v1, v2, lson);
else
update(p, v1, v2, rson);
pushup(rt);
}
int query(int L, int R, int l, int r, int rt, bool flag) {
if (L <= l && r <= R) {
if (flag)
return A[rt];
else
return B[rt];
}
int m = (l + r) >> 1;
int t = INF;
if (L <= m)
t = min(t, query(L, R, lson, flag));
if (m < R)
t = min(t, query(L, R, rson, flag));
return t;
}
} tree;
struct node {
int x, y, id;
node() {
}
node(int x, int y, int id) :
x(x), y(y), id(id) {
}
bool operator<(const node &t) const {
return x < t.x || (x == t.x && y < t.y);
}
} f[maxn];
int Y[maxn], ans[maxn], pos[maxn];
int binary_search(int l, int r, int k) {
int m;
while (l <= r) {
m = (l + r) >> 1;
if (Y[m] == k)
return m;
if (Y[m] < k)
l = m + 1;
else
r = m - 1;
}
return m;
}
int main() {
int id, k, cnt, n, i, m, x, y, c, p, cas = 0;
//freopen("D:\\C.in","r",stdin);
while (scanf("%d", &n) && n >= 0) {
if (cas++)
puts("");
cnt = c = 0;
for (i = 0; i < n; ++i) {
scanf("%d%d", &x, &y);
f[cnt] = node(x, y, -1);
Y[cnt++] = y;
}
scanf("%d", &m);
for (i = 0; i < m; ++i) {
scanf("%d%d", &x, &y);
ans[i] = INF;
f[cnt] = node(x, y, i);
Y[cnt++] = y;
}
sort(Y, Y + cnt);
sort(f, f + cnt);
k = unique(Y, Y + cnt) - Y;
for (i = 0; i < cnt; ++i) {
pos[i] = binary_search(0, k - 1, f[i].y) + 1;
}
tree.build(1, k, 1);
int a, b;
for (i = 0; i < cnt; ++i) {
id = f[i].id;
p = pos[i];
x = f[i].x;
y = f[i].y;
if (~id) {
a = tree.query(1, p, 1, k, 1, 1);
b = tree.query(p, k, 1, k, 1, 0);
if (a < INF)
ans[id] = min(ans[id], x + y + a);
if (b < INF)
ans[id] = min(ans[id], x - y + b);
//printf("%d %d %d %d %d %d\n", a, b, x, y, i, ans[id]);
} else
tree.update(p, -x - y, y - x, 1, k, 1);
}
tree.build(1, k, 1);
for (i = cnt - 1; i >= 0; --i) {
id = f[i].id;
p = pos[i];
x = f[i].x;
y = f[i].y;
if (~id) {
a = tree.query(1, p, 1, k, 1, 1);
b = tree.query(p, k, 1, k, 1, 0);
if (a < INF)
ans[id] = min(ans[id], -x + y + a);
if (b < INF)
ans[id] = min(ans[id], -x - y + b);
} else
tree.update(p, x - y, x + y, 1, k, 1);
}
for (i = 0; i < m; ++i)
printf("%d\n", ans[i]);
}
return 0;
}
HDU 4189
最新推荐文章于 2017-07-01 23:33:30 发布