bzoj 3781: 小B的询问

3781: 小B的询问

Time Limit: 10 Sec Memory Limit: 128 MB
Submit: 593 Solved: 402
[Submit][Status][Discuss]
Description

小B有一个序列,包含N个1~K之间的整数。他一共有M个询问,每个询问给定一个区间[L..R],求Sigma(c(i)^2)的值,其中i的值从1到K,其中c(i)表示数字i在[L..R]中的重复次数。小B请你帮助他回答询问。
Input

第一行,三个整数N、M、K。
第二行,N个整数,表示小B的序列。
接下来的M行,每行两个整数L、R。
Output

M行,每行一个整数,其中第i行的整数表示第i个询问的答案。
Sample Input

6 4 3

1 3 2 1 1 3

1 4

2 6

3 5

5 6

Sample Output

6

9

5

2

HINT

对于全部的数据,1<=N、M、K<=50000


【分析】
裸的无修改莫队
新增莫队算法条件:增减区间暴力扫时可以用题目所给或自己总结出的关系式更新答案


【代码】

//【bzoj3781】小B的询问
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#define fo(i,j,k) for(i=j;i<=k;i++)
using namespace std;
struct node
{
    int l,r,id;
}q[50001];
inline bool comp_l(const node &x,const node &y) {return x.l<y.l;}
inline bool comp_r(const node &x,const node &y) {if(x.r==y.r) return x.l<y.l;return x.r<y.r;}
int n,m,k,sum;
int a[50001],c[50001],ans[50001];
inline void add(int x)
{
    c[x]++;
    sum+=c[x]+c[x]-1;
}
inline void del(int x)
{
    c[x]--;
    sum-=(c[x]+c[x]+1);
}
int main()
{
    int i,j;
    scanf("%d%d%d",&n,&m,&k);
    fo(i,1,n)
      scanf("%d",&a[i]);
    fo(i,1,m)
    {
        scanf("%d%d",&q[i].l,&q[i].r);
        q[i].id=i;
    }
    sort(q+1,q+m+1,comp_l);
    i=1;j=0;
    int x=sqrt(n);
    while(i<=m)
    {
        j++;
        int b=i;
        while(q[i].l<=j*x && i<=m) i++;
        sort(q+b,q+i,comp_r);
        if(j==x)
          sort(q+b,q+m+1,comp_r);
    }
    int ll=1,rr=0;
    fo(i,1,m)
    {
        if(ll<q[i].l)
          fo(j,ll,q[i].l-1)
            del(a[j]);
        else
          fo(j,q[i].l,ll-1)
            add(a[j]);
        ll=q[i].l;
        if(rr<q[i].r)
          fo(j,rr+1,q[i].r)
            add(a[j]);
        else
          fo(j,q[i].r+1,rr)
            del(a[j]);
        rr=q[i].r;
        ans[q[i].id]=sum;
    }
    fo(i,1,m)
      printf("%d\n",ans[i]);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值