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
| #include <bits/stdc++.h> #define ls(p) (p<<1) #define rs(p) (p<<1|1) #define fi first #define se second using namespace std; const int N = 500000 + 5; const int inf = 0x3f3f3f3f; int n, m; vector <pair<int , int> > q[N]; int pre[N], tmp[N], a[N]; int mn[N<<2], mnp[N<<2], ans[N<<2]; void Pushup(int p) { if(mn[ls(p)] < mn[rs(p)]) {mn[p] = mn[ls(p)]; mnp[p] = mnp[ls(p)];} else {mn[p] = mn[rs(p)]; mnp[p] = mnp[rs(p)];} } void Build(int p, int l, int r) { if(l == r) { mn[p] = inf; mnp[p] = a[l]; return ; } int mid = (l + r) >> 1; Build(ls(p), l, mid); Build(rs(p), mid + 1, r); Pushup(p); } void Update(int p, int x, int y, int l, int r) { if(l == r) { mn[p] = y; return; } if(x < l || x > r) return ; int mid = (l + r) >> 1; if(x <= mid) Update(ls(p), x, y, l, mid); else Update(rs(p), x, y, mid + 1, r); Pushup(p); }
pair<int, int> Query(int p, int ql, int qr, int l, int r) { if(ql <= l && r <= qr) return {mn[p], mnp[p]}; int mid = (l + r) >> 1; pair <int, int> ret = {inf, 0}; if(ql <= mid) ret = min(ret, Query(ls(p), ql, qr, l, mid)); if(qr > mid) ret = min(ret, Query(rs(p), ql, qr, mid + 1, r)); return ret; } int main() { scanf("%d", &n); for(int i = 1; i <= n; i++) scanf("%d", &a[i]), pre[i] = tmp[a[i]], tmp[a[i]] = i; scanf("%d", &m); for(int i = 1; i <= m; i++) { int l, r; scanf("%d%d", &l, &r); q[r].push_back({l, i}); }
Build(1, 1, n); for(int i = 1; i <= n; i++) { Update(1, i, pre[i], 1, n); if(pre[i]) Update(1, pre[i], inf, 1, n); for(int j = 0; j < q[i].size(); j++) { int l = q[i][j].fi, id = q[i][j].se; pair <int, int> node = Query(1, l, i, 1, n); if(node.fi < l) { ans[id] = node.se; } else ans[id] = 0; } } for(int i = 1; i <= m; i++) printf("%d\n", ans[i]); return 0; }
|