BZOJ 1878 HH的项链

莫队

还是一道模板。。不过洛谷数据加强了,必须要奇偶性排序+吸氧才能过,BZOJ可以直接过的~

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
    int X = 0, w = 0; char ch = 0;
    while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
    while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
    return w ? -X : X;
}
inline int gcd(int a, int b){ return b ? gcd(b, a % b) : a; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
    A ans = 1;
    for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
    return ans;
}
const int N = 500005;
const int M = 1000005;

int n, m, t, a[N], freq[M], ans, res[N];
struct Query{
    int l, r, id, block;
    bool operator < (const Query &rhs) const {
        return (block ^ rhs.block) ? l < rhs.l : (block & 1) ? r < rhs.r : r > rhs.r;
    }
}query[N];

inline void add(int k){
    freq[a[k]] ++;
    if(freq[a[k]] == 1) ans ++;
}

inline void remove(int k){
    freq[a[k]] --;
    if(freq[a[k]] == 0) ans --;
}

int main(){

    n = read();
    for(int i = 1; i <= n; i ++) a[i] = read();
    m = read();
    t = (int)sqrt(n);
    for(int i = 1; i <= m; i ++){
        query[i].l = read(), query[i].r = read();
        query[i].id = i, query[i].block = (query[i].l - 1) / t + 1;
    }
    sort(query + 1, query + m + 1);
    int l = 1, r = 0;
    for(int i = 1; i <= m; i ++){
        int curL = query[i].l, curR = query[i].r;
        while(l < curL) remove(l ++);
        while(l > curL) add(-- l);
        while(r < curR) add(++ r);
        while(r > curR) remove(r --);
        res[query[i].id] = ans;
    }
    for(int i = 1; i <= m; i ++){
        printf("%d\n", res[i]);
    }
    return 0;
}
posted @ 2019-05-13 18:58  清楚少女ひなこ  阅读(98)  评论(0编辑  收藏  举报