51nod 1290 Counting Diff Pairs

本文通过一个具体的题目实例,详细介绍了如何使用莫队算法解决区间查询问题。文章首先概述了问题背景,接着给出了具体实现思路,包括数据离散化、整体二分技巧以及树状数组的应用,并最终提供了完整的代码实现。

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

原题链接.

看到n <= 50000就要有莫队的敏感度。

某infleaking说也许整体二分套个数据结构是行的。

离散一下,直接莫队,用个常数小的树状数组维护一下就行了。

理论复杂度: O(nn log n)1.6109

加上那么一点小常数也许会T。

可是我才跑了1.6s,时限4s,……

Code:

#include<cstdio>
#include<cstring>
#include<algorithm>
#define fo(i, x, y) for(int i = x; i <= y; i ++)
#define low(x) ((x) & -(x))
using namespace std;

const int N = 5e4 + 5;

int n, k, Q, a[N];
struct node {
    int i, x;
} b[N];
struct Ask {
    int i, l, r;    
} c[N];
const int M = 223;
int num[N], to[N];
int st[N], en[N];

bool rank(node a, node b) {return a.x < b.x;}

void Build() {
    num[0] = 0;
    fo(i, 1, n) {
        num[i] = num[i - 1];
        if((i - 1) % M == 0) num[i] ++;
    }
}

void Build_se() {
    fo(i, 1, n) {
        int z = b[i].i;
        for(int x = 1, y = i; x <= y; ) {
            int m = x + y >> 1;
            if(b[i].x - b[m].x <= k)
                st[z] = m, y = m - 1; else x = m + 1;
        }
        for(int x = i, y = n; x <= y; ) {
            int m = x + y >> 1;
            if(b[m].x - b[i].x <= k)
                en[z] = m, x = m + 1; else y = m - 1;
        }
    }
}

bool rank_c(Ask a, Ask b) {
    if(num[a.l] < num[b.l]) return 1;
    if(num[a.l] > num[b.l]) return 0;
    return a.r < b.r;
}

int bz[N], f[N], ans[N], sum;

void add(int x, int y) {while(x <= n) f[x] += y, x += low(x);}
int qiu(int x) {int s = 0; while(x) s += f[x], x -= low(x); return s;}
int Sum(int x, int y) {return qiu(y) - qiu(x - 1);}
void chan(int x) {
    int f = bz[x] ? -1 : 1; bz[x] = !bz[x];
    if(f == -1) {
        add(to[x], f);
        sum += f * Sum(st[x], en[x]);
    } else {
        sum += f * Sum(st[x], en[x]);
        add(to[x], f);
    }
}

int main() {
    scanf("%d %d %d", &n, &k, &Q);
    fo(i, 1, n) scanf("%d", &a[i]), b[i].i = i, b[i].x = a[i];
    sort(b + 1, b + n + 1, rank);
    fo(i, 1, n) to[b[i].i] = i;
    Build();
    Build_se();
    fo(i, 1, Q) scanf("%d %d", &c[i].l, &c[i].r), c[i].l ++, c[i].r ++, c[i].i = i;
    sort(c + 1, c + Q + 1, rank_c);
    int x = 1, y = 0;
    fo(i, 1, Q) {
        while(x < c[i].l) chan(x ++);
        while(x > c[i].l) chan(-- x);
        while(y < c[i].r) chan(++ y);
        while(y > c[i].r) chan(y --);
        ans[c[i].i] = sum;
    }
    fo(i, 1, Q) printf("%d\n", ans[i]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值