牛客网暑期ACM多校训练营(第一场)J Different Integers【莫队】

题意:给你n个数,q个查询,问你在 [L+1,R1] [ L + 1 , R − 1 ] 这段区间之外有多少个不同的数.
分析:
满足莫队思想,直接莫队处理会TLE,把不正规的区间删去,在用莫队处理就行了。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long LL;

int const size = 100010;
int const block_size = 400;
int A[size], cnt[size] = {0};
int ans[size], ma[size];
int n, q, num, sum, p;

struct node{
    int s, e;
    int id;
}B[size];

bool operator < (node const& x,node const& y){
    int ln = x.s / block_size;
    int rn = y.s / block_size;
    return ln < rn || ( ln == rn && x.e < y.e );
}

inline void insert(int x) {
    ++cnt[x];
    if(cnt[x] == ma[x]) num--;
}

inline void remove(int x) {
    if(cnt[x] == ma[x]) num++;
    --cnt[x];
}

inline void Modui() {
    sort(B, B + p);
    int Left = 1, Right = 0;
    for(int i = 0; i < p; ++i) {
        while(Right < B[i].e) insert(A[++Right]);
        while(Left > B[i].s)  insert(A[--Left]);
        while(Right > B[i].e) remove(A[Right--]);
        while(Left < B[i].s)  remove(A[Left++]);
        ans[B[i].id] = num;
    }
    for(int i = 0; i < q; ++i) printf("%d\n", ans[i] ? ans[i] : sum);
}

inline int Scan() { //输入挂 
    int res = 0, ch;
    while(!((ch = getchar()) >= '0' && ch <= '9')) {
        if(ch == EOF) return 1 << 30;
    }
    res = ch - '0';
    while((ch = getchar()) >= '0' && ch <= '9')
        res = res * 10 + ( ch - '0');
    return res;
}

inline void read() {
    while(scanf("%d %d", &n, &q) != EOF) {
        memset(cnt, 0, sizeof(cnt));
        memset(ma, 0, sizeof(ma));
        memset(ans, 0, sizeof(ans));
        num = p = 0;
        for(int i = 1; i <= n; ++i) {
            A[i] = Scan();
            if(!ma[A[i]]) num++;
            ma[A[i]]++;
        }
        sum = num;
        int t1, t2;
        for(int i = 0; i < q; ++i) {
            t1 = Scan();
            t2 = Scan();
            if(++t1 > --t2) continue; //把不正规的区间给删去 
            B[p].s = t1, B[p].e = t2;
            B[p++].id = i;
        }
        Modui();
    }
}

int main() {
    read();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值