1. 程式人生 > >SPOJ3267:D-query

SPOJ3267:D-query

gpo tps 序列 pac 線段 net mod https query

題面

SPOJ3267

Sol

給定\(N\)個正整數構成的序列,將對於指定的閉區間查詢其區間內的不同的數的個數

主席樹
不是權值線段樹
維護位置
如果插入一個數時發現之前有過了
那麽修改當前的,那個位置\(-1\)
然後插入這個數字,在相應的位置\(+1\)

# 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 _(3e4
+ 5); const int __(1e6); 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; } int main(RG int argc, RG char* argv[]){ n = 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 = 1; i <= n; ++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); } } m = Input(); for(RG int i = 1; i <= m; ++i){ RG int l = Input(), r = Input(); printf("%d\n", Query(rt[r], 1, n, l, r)); } return 0; }

SPOJ3267:D-query