1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| #include <cstdio> #include <vector> using namespace std; template <class Type> void read(Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; flag && (x = ~x + 1); } template <class Type> void write(Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar(x % 10 + '0'); } template <class Type> void chkmin (Type &x, Type k) { k < x && (x = k); } template <class Type> void chkmax (Type &x, Type k) { (x < k) && (x = k); } const int N = 1e5 + 10, Q = 3e5 + 10, inf = 1e9; int n, m, w[N], ans[Q]; struct Query { int l, id; }; vector <Query> q[N]; namespace BIT { int tr[N]; void init() { for (int i = 1; i <= n; i++) tr[i] = inf; } void modify (int x, int k) { for (; x; x -= x & -x) chkmin(tr[x], k); } int query (int x) { int res = inf; for (; x <= n; x += x & -x) chkmin(res, tr[x]); return res; } } namespace PresidentTree { const int M = 9e6 + 10; struct Node { int l, r, v; } tr[M]; int rt, idx; void init() { for (int i = 1; i <= idx; i++) tr[i].l = tr[i].r = tr[i].v = 0; rt = idx = 0; } void modify (int &x, int t, int k, int l = 0, int r = inf) { !x && (x = ++idx); chkmax(tr[x].v, k); if (l == r) return; int mid = l + r >> 1; t <= mid ? modify(tr[x].l, t, k, l, mid) : modify(tr[x].r, t, k, mid + 1, r); } int query (int L, int R, int l = 0, int r = inf, int x = rt) { if (!x || l > R || L > r) return 0; if (l >= L && r <= R) return tr[x].v; int mid = l + r >> 1; return max(query(L, R, l, mid, tr[x].l), query(L, R, mid + 1, r, tr[x].r)); } } void solve () { BIT::init(), PresidentTree::init(); for (int i = 1; i <= n; i++) { int t = PresidentTree::query(w[i], inf); while (t) { BIT::modify(t, w[t] - w[i]); t = PresidentTree::query(w[i], w[i] + w[t] - 1 >> 1); } PresidentTree::modify(PresidentTree::rt, w[i], i); for (Query j : q[i]) chkmin(ans[j.id], BIT::query(j.l)); } } int main () { read(n); for (int i = 1; i <= n; i++) read(w[i]); read(m); for (int i = 1, l, r; i <= m; i++) { read(l), read(r); ans[i] = inf; q[r].push_back((Query){l, i}); } solve(); for (int i = 1; i <= n; i++) w[i] = inf - w[i]; solve(); for (int i = 1; i <= m; i++) write(ans[i]), puts(""); return 0; }
|