【bzoj1878】[SDOI2009]HH的项链

莫队裸题。

#include 
#define rep(i,a,b) for(int i=a,_=b;i<=_;i++)
#define per(i,a,b) for(int i=a,_=b;i>=_;i--)
#define maxn 50007
#define maxm 200007

inline int rd() {
    char c = getchar();
    while (!isdigit(c)) c = getchar() ; int x = c - '0';
    while (isdigit(c = getchar())) x = x * 10 + c - '0';
    return x;
}

int len;

struct query {
    int l , r , t;
    bool operator<(const query x) const {
        if (l / len == x.l / len) return r < x.r;
        return l / len < x.l / len;
    }
}q[maxm];

int n , m , res[maxm] , a[maxn] , ans;
int cnt[maxm * 5 + 1];

void input() {
    n = rd();
    len = (int) sqrt(n + 0.5);
    rep (i , 1 , n) a[i] = rd();
    m = rd();
    rep (i , 1 , m) q[i].l = rd() , q[i].r = rd() , q[i].t = i;
    std::sort (q + 1 , q + m + 1);
}

void solve() {
    cnt[a[1]] = 1 , ans = 1;
    for (int i = 1 , l = 1 , r = 1;i <= m;i ++) {
        for (;r < q[i].r;) ++ r , ans += (cnt[a[r]] ++ == 0);
        for (;r > q[i].r;) ans -= (cnt[a[r]] -- == 1) , r --;
        for (;l > q[i].l;) -- l , ans += (cnt[a[l]] ++ == 0);
        for (;l < q[i].l;) ans -= (cnt[a[l]] -- == 1) , l ++;
        res[q[i].t] = ans;
    }
    rep (i , 1 , m) printf("%d\n" , res[i]);
}

int main() {
    #ifndef ONLINE_JUDGE
        freopen("data.txt" , "r" , stdin);
    #endif
    input();
    solve();
    return 0;
}


你可能感兴趣的:(莫队算法,水题)