分块/莫队算法Codeforces86D

本文提供了一道CodeForces平台上的难题D的详细解答,采用分块算法优化查询过程,通过预处理和动态更新策略减少时间复杂度,适用于算法竞赛及数据结构学习。

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

题目链接:http://codeforces.com/contest/86/problem/D

#include <bits/stdc++.h>

using namespace std;
using ll = long long ;
const int N = 1E6 + 7;
int a[N], belong[N], BLOCK, sum[N];
ll res, ans[N];
struct node
{
    int l, r, id;
    bool operator < (const node & x) const {
        if(belong[l] == belong[x.l]) return r < x.r;
        else return l < x.l;
    }
}Q[N];
void modify(int p, int add)
{
    res -= a[p] * 1ll * sum[a[p]] * sum[a[p]];
    sum[a[p]] += add;
    res += a[p] * 1ll * sum[a[p]] * sum[a[p]];
}
int main()
{
    int n, t;
    scanf("%d%d",&n,&t);
    BLOCK = sqrt(n);
    for(int i = 1;i <= n;i ++) scanf("%d",&a[i]), belong[i] = (i - 1) / BLOCK + 1;
    for(int i = 1;i <= t;i ++) {
        scanf("%d%d",&Q[i].l,&Q[i].r);
        Q[i].id = i;
    }
    sort(Q+1, Q+1+t);
    for(int i = 1, l = 1, r = 0;i <= t;i ++) {
        for(;r < Q[i].r; r ++) modify(r+1, 1);
        for(;r > Q[i].r; r --) modify(r, -1);
        for(;l < Q[i].l; l ++) modify(l, -1);
        for(;l > Q[i].l; l --) modify(l-1, 1);
        ans[Q[i].id] = res;
    }
    for(int i = 1; i <= t; i ++) printf("%lld\n",ans[i]);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值