莫队10pts求助
查看原帖
莫队10pts求助
483928
Z1qqurat楼主2023/7/19 21:45

直接莫队求区间众数,但是寄了,求大佬看看qwq

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
#define ll long long
#define pii pair<int, int>
#define mr make_pair
using namespace std;
const int N = 2e5 + 5;
int n, m, t, a[N], b[N], tot, cnt[N], num[N], ans, res[N];
// tot表示a[i]中不重复的元素个数,cnt[i]表示离散化后的i的出现次数,num[i]表示出现次数为i的数的个数
// ans表示区间众数的出现次数,ret[i]表示第i个询问的答案
struct Qu{
    int l, r, id, bel;
}q[N];

bool cmp(Qu x, Qu y) {
    if(x.bel == y.bel) {
        if(x.bel & 1) return x.r < y.r;
        return x.r > y.r;
    }
    return x.bel < y.bel;
}

void Del(int x) {
    if(ans == cnt[a[x]] && num[cnt[a[x]]] == 1) ans--;
    num[cnt[a[x]]]--, cnt[a[x]]--;
    num[cnt[a[x]]]++;
    return ;
}

void Add(int x) {
    if(ans < cnt[a[x]] + 1) ans++;
    num[cnt[a[x]]]--, cnt[a[x]]++;
    num[cnt[a[x]]]++;
    return ;
}

int main() {
    scanf("%d %d", &n, &m);
    t = sqrt(n);
    for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
    memcpy(b, a, sizeof(a));
    tot = unique(b + 1, b + n + 1) - b - 1;
    for (int i = 1; i <= n; ++i) {
        a[i] = lower_bound(b + 1, b + tot + 1, a[i]) - b;
    }
    for (int i = 1; i <= m; ++i) {
        scanf("%d %d", &q[i].l, &q[i].r);
        q[i].id = i, q[i].bel = q[i].l / t;
    }
    sort(q + 1, q + m + 1, cmp);
    int lt = 0, rt = 0;
    for (int i = 1; i <= m; ++i) {
        int qx = q[i].l, qy = q[i].r;
        while(lt > qx) Add(--lt);
        while(rt < qy) Add(++rt);
        while(lt < qx) Del(lt++);
        while(rt > qy) Del(rt--);
        res[q[i].id] = -ans;
    }
    for (int i = 1; i <= m; ++i) printf("%d\n", res[i]);
    return 0;
}
2023/7/19 21:45
加载中...