洛谷P2709 小B的询问

本文深入探讨了莫队算法的基本原理及其实现细节,通过一道模板题详细展示了如何利用莫队算法解决区间查询问题,包括序列分块、询问排序等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

莫队模版

本来想能不学莫队就不学,但是这次比赛被莫队卡得好惨,于是学了一发。。

先切道模板题。。

最普通的莫队就是把序列分块,然后按照询问所在的块来排序,减少指针的移动次数。。

#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 = 50005;
int n, m, k, a[N], cnt[N], 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];

void add(int k){
    cnt[a[k]] ++;
    ans += 2 * cnt[a[k]] - 1;
}

void remove(int k){
    cnt[a[k]] --;
    ans += -2 * cnt[a[k]] - 1;
}

int main(){

    n = read(), m = read(), k = read();
    int t = (int)sqrt(n);
    for(int i = 1; i <= n; i ++) a[i] = read();
    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(r < curR) add(++ r);
        while(l > curL) add(-- l);
        while(r > curR) remove(r --);
        res[query[i].id] = ans;
    }
    for(int i = 1; i <= m; i ++){
        printf("%d\n", res[i]);
    }
    return 0;
}

转载于:https://www.cnblogs.com/onionQAQ/p/10858207.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值