CodeForces - 86D Powerful array

本文介绍了一个使用莫队算法解决特定区间查询问题的例子。通过详细解释代码实现,展示了如何高效地处理一系列区间内的元素操作和查询任务。

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

题目:给你n个数,m个询问,Ks为区间[l,r]中s出现的次数,求区间[l,r]中所有的Ks*Ks*s的和。

思路:莫队算法

代码:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<list>
#include<numeric>
using namespace std;
#define PI acos(-1.0)
#define LL __int64
#define ULL unsigned long long
#define INF 0x3f3f3f3f
#define mm(a,b) memset(a,b,sizeof(a))
#define PP puts("*********************");
template<class T> T f_abs(T a){ return a > 0 ? a : -a; }
template<class T> T gcd(T a, T b){ return b ? gcd(b, a%b) : a; }
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
// 0x3f3f3f3f3f3f3f3f
// 0x3f3f3f3f

const int maxn=1e6+50;
struct Ask{
    int L,R,id;
}ask[maxn];
LL ans[maxn];
int arr[maxn],num[maxn];//从1开始计数
int n,m,siz;//n个数,m个询问,块的大小
bool cmp(Ask a,Ask b){
    if(a.L/siz!=b.L/siz) return a.L/siz<b.L/siz;
    else return a.R<b.R;
}
void solve(){
    LL temp=0;
    mm(num,0);
    int L=1,R=0;
    for(int i=1;i<=m;i++){
        while(R<ask[i].R){
            R++;
            temp-=(LL)num[arr[R]]*num[arr[R]]*arr[R];
            num[arr[R]]++;
            temp+=(LL)num[arr[R]]*num[arr[R]]*arr[R];
        }
        while(R>ask[i].R){
            temp-=(LL)num[arr[R]]*num[arr[R]]*arr[R];
            num[arr[R]]--;
            temp+=(LL)num[arr[R]]*num[arr[R]]*arr[R];
            R--;
        }
        while(L<ask[i].L){
            temp-=(LL)num[arr[L]]*num[arr[L]]*arr[L];
            num[arr[L]]--;
            temp+=(LL)num[arr[L]]*num[arr[L]]*arr[L];
            L++;
        }
        while(L>ask[i].L){
            L--;
            temp-=(LL)num[arr[L]]*num[arr[L]]*arr[L];
            num[arr[L]]++;
            temp+=(LL)num[arr[L]]*num[arr[L]]*arr[L];
        }
        ans[ask[i].id]=temp;
    }
}
int main(){

    while(~scanf("%d%d",&n,&m)){
        for(int i=1;i<=n;i++)
            scanf("%d",&arr[i]);
        for(int i=1;i<=m;i++){
            ask[i].id=i;
            scanf("%d%d",&ask[i].L,&ask[i].R);
        }
        siz=(int)sqrt(n*1.0);
        sort(ask+1,ask+m+1,cmp);
        solve();
        for(int i=1;i<=m;i++)
            printf("%I64d\n",ans[i]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值