HDU5919:Sequence II

题面

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;
}

posted @ 2018-02-28 22:41  Cyhlnj  阅读(191)  评论(0编辑  收藏  举报