P2709 小B的询问(莫队)

在这里插入图片描述
在这里插入图片描述

#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <iostream>
#include <math.h>
using namespace std;
int n, m, k, bbclock, a[1000001], cnt = 0, ans1 = 0;
struct node
{
    int l, r, id;
} b[1000001];
int c[1000001], ans[1000001];
bool cmp(struct node a, struct node b)
{
    if ((a.l / bbclock) == (b.l / bbclock))
    {
        return a.r > b.r;
    }
    else
    {
        return (a.l / bbclock) < (b.l / bbclock);
    }
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
#endif
    int i, j, l, r, q = 0, L, R;
    scanf("%d %d %d", &n, &m, &k);
    bbclock = sqrt(n);
    L = 1, R = n;
    for (i = 1; i < n + 1; i++)
    {
        scanf("%d", &a[i]);
        c[a[i]]++;
    }
    ans1=0;
    for(i=1;i<k+1;i++)
    {
        ans1+=c[i]*c[i];
    }
    for (i = 1; i < m + 1; i++)
    {
        scanf("%d %d", &b[cnt].l, &b[cnt].r);
        b[cnt].id = i;
        cnt++;
    }
    sort(b, b + cnt, cmp);
    for (i = 0; i < cnt; i++)
    {
        while (L < b[i].l)
        {
            
            ans1 = ans1 - 2 * c[a[L]] + 1;
            c[a[L]]--;
            L++;
        }
        while (L > b[i].l)
        {
            
            L--;
            ans1 += 2 * c[a[L]] + 1;
            c[a[L]]++;
        }
        while (R <b[i].r)
        {
            R++;
            ans1 += 2 * c[a[R]] + 1;
            c[a[R]]++;
        }
        while (R > b[i].r)
        {
            
            ans1 = ans1 - 2 * c[a[R]] + 1;
            c[a[R]]--;
            R--;
        }
        ans[b[i].id] = ans1;
    }
    for (i = 1; i < m+1; i++)
    {
        printf("%d\n", ans[i]);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值