1. 程式人生 > >HDU5919:Sequence II

HDU5919:Sequence II

所有 seq names span bits ans code 每次 return

題面

Vjudge

Sol

給一個數列,有m個詢問,每次問數列[l,r]區間中所有數的第一次出現的位置的中位數是多少,強制在線

主席樹
詢問區間內不同的數的個數
樹上二分找到那個中位數

# include <bits/stdc++.h>
# define RG register
# define IL inline
# define Fill(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(2e5 + 5);
const int __(8e6);

IL int Input(){
    RG int
x = 0, z = 1; RG char c = getchar(); for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1; for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48); return x * z; } int n, m, rt[_], tot, o[_], len, a[_], vis[_]; struct
HJT{ int ls, rs, sz; } T[__]; IL void Modify(RG int &x, RG int l, RG int r, RG int p, RG int v){ T[++tot] = T[x], T[x = tot].sz += v; if(l == r) return; RG int mid = (l + r) >> 1; if(p <= mid) Modify(T[x].ls, l, mid, p, v); else Modify(T[x].rs, mid + 1, r, p, v); } IL int
Query(RG int x, RG int l, RG int r, RG int L, RG int R){ if(!x) return 0; if(L <= l && R >= r) return T[x].sz; RG int mid = (l + r) >> 1, ret = 0; if(L <= mid) ret = Query(T[x].ls, l, mid, L, R); if(R > mid) ret += Query(T[x].rs, mid + 1, r, L, R); return ret; } IL int Calc(RG int x, RG int l, RG int r, RG int k){ if(l == r) return l; RG int mid = (l + r) >> 1, s = T[T[x].ls].sz; if(k <= s) return Calc(T[x].ls, l, mid, k); return Calc(T[x].rs, mid + 1, r, k - s); } int main(RG int argc, RG char* argv[]){ for(RG int t = Input(), Case = 1; Case <= t; ++Case){ Fill(T, 0), Fill(rt, 0), Fill(vis, 0), tot = 0; n = Input(), m = Input(); for(RG int i = 1; i <= n; ++i) o[i] = a[i] = Input(); sort(o + 1, o + n + 1), len = unique(o + 1, o + n + 1) - o - 1; for(RG int i = n; i; --i){ a[i] = lower_bound(o + 1, o + len + 1, a[i]) - o; rt[i] = rt[i + 1]; if(!vis[a[i]]) vis[a[i]] = i, Modify(rt[i], 1, n, i, 1); else{ Modify(rt[i], 1, n, vis[a[i]], -1); vis[a[i]] = i; Modify(rt[i], 1, n, i, 1); } } printf("Case #%d:", Case); for(RG int i = 1, ans = 0; i <= m; ++i){ RG int l = Input(), r = Input(), ql, qr, num; ql = min((l + ans) % n + 1, (r + ans) % n + 1); qr = max((l + ans) % n + 1, (r + ans) % n + 1); num = Query(rt[ql], 1, n, ql, qr); printf(" %d", ans = Calc(rt[ql], 1, n, (num + 1) >> 1)); } puts(""); } return 0; }

HDU5919:Sequence II