P2709 小B的询问【莫队】

题目描述
小B有一个序列,包含N个1~K之间的整数。他一共有M个询问,每个询问给定一个区间[L..R],求Sigma(c(i)^2)的值,其中i的值从1到K,其中c(i)表示数字i在[L..R]中的重复次数。小B请你帮助他回答询问。
输入输出格式
输入格式:
第一行,三个整数N、M、K。
第二行,N个整数,表示小B的序列。
接下来的M行,每行两个整数L、R。
输出格式
M行,每行一个整数,其中第i行的整数表示第i个询问的答案。
输入输出样例
输入样例#1: 复制
6 4 3
1 3 2 1 1 3
1 4
2 6
3 5
5 6
输出样例#1: 复制
6
9
5
2

分析:
莫队算法(暴力):适用于多次区间查询问题,且由 [L,R] [ L , R ] 能推到 [L1,R] [ L − 1 , R ] , [L+1,R] [ L + 1 , R ] , [L,R1] [ L , R − 1 ] , [L,R+1] [ L , R + 1 ] .
其实就是把查询排序,由于相邻之间有关系,查找区间尽可能相近,移动步数就较少,复杂度 nsqrt(n) n ∗ s q r t ( n ) .

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

int const size = 60100;
int const block_size = 250; //分块的大小
int A[size], cnt[200010] = {0};
LL ans[200010];
int n, q, k;
LL sum;

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

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){
    sum = sum + cnt[x] * 2 + 1;
    ++cnt[x];
}

inline void remove(int x){
    --cnt[x];
    sum = sum - cnt[x] * 2 - 1;
}

void Modui() {
    sort(B, B + q);
    int Left = 1, Right = 0;
    sum = 0;
    for(int i = 0; i < q; ++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] = sum;
    }
    for(int i = 0; i < q; ++i) printf("%lld\n", ans[i]);
}

void read() {
    scanf("%d %d %d", &n, &q, &k);
    for(int i = 1; i <= n; ++i) scanf("%d", A + i);//数据下标1~n
    for(int i = 0; i < q; ++i) { //询问下标1~q - 1
        scanf("%d %d", &B[i].s, &B[i].e);
        B[i].id = i;
    }
}

int main() {
    read(); //读入数据
    Modui();//莫队模板
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值