【CodeForces Yandex Algorithm 2011 D】【莫队分块】区间所有数值乘其数个数的平方

#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<math.h>
#include<iostream>
#include<string>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<bitset>
#include<algorithm>
#include<time.h>
using namespace std;
void fre(){freopen("c://test//input.in","r",stdin);freopen("c://test//output.out","w",stdout);}
#define MS(x,y) memset(x,y,sizeof(x))
#define MC(x,y) memcpy(x,y,sizeof(x))
#define MP(x,y) make_pair(x,y)
#define ls o<<1
#define rs o<<1|1
typedef long long LL;
typedef unsigned long long UL;
typedef unsigned int UI;
template <class T> inline void gmax(T &a,T b){if(b>a)a=b;}
template <class T> inline void gmin(T &a,T b){if(b<a)a=b;}
const int N=2e5+10,M=1e6+10,Z=1e9+7,ms63=1061109567;
int n,m;
LL v[N],ans[N];
int num[M];
struct A
{
    int l,r,id,o;
    bool operator < (const A& b)const
    {
        if(id!=b.id)return id<b.id;
        return r<b.r;
    }
}a[N];
LL ins(int p)
{
    LL x=v[p];
    ++num[x];
    return x*(num[x]*num[x]-(num[x]-1)*(num[x]-1));
}
LL del(int p)
{
    LL x=v[p];
    --num[x];
    return x*(num[x]*num[x]-(num[x]+1)*(num[x]+1));
}
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        MS(num,0);
        int len=sqrt(n);
        for(int i=1;i<=n;i++)scanf("%lld",&v[i]);
        for(int i=1;i<=m;i++)
        {
            scanf("%d%d",&a[i].l,&a[i].r);
            a[i].id=a[i].l/len;
            a[i].o=i;
        }
        sort(a+1,a+m+1);
        int l=a[1].l;
        int r=l-1;
        LL ANS=0;
        for(int i=1;i<=m;i++)
        {
            while(l>a[i].l)ANS+=ins(--l);
            while(r<a[i].r)ANS+=ins(++r);
            while(l<a[i].l)ANS+=del(l++);
            while(r>a[i].r)ANS+=del(r--);
            ans[a[i].o]=ANS;
        }
        for(int i=1;i<=m;i++)printf("%lld\n",ans[i]);
    }
    return 0;
}
/*
【trick&&吐槽】
小心爆int!

【题意】
http://codeforces.com/contest/86/my
给你一个数列,有n(2e5)个数和m(2e5)个询问。
每个数的范围是1e6
对于每个询问,你要求出区间[l,r]内,所有数字出现个数的平方*数字。

【类型】
莫队分块算法

【分析】
1,这道题是关于区间询问的。
2,如果区间边界左右移动,询问答案可以以O(1)的复杂度即时更新

于是我们就可以用莫队分块算法来解决这道题

【时间复杂度&&优化】
O(n^1.5)

【数据】
Sample test(s)
Input
3 2
1 2 1
1 2
1 3

Output
3
6

Input
8 3
1 1 2 2 1 3 1 1
2 7
1 6
2 7

Output
20
20
20

*/
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值