• P2709 小B的询问


    题目描述

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

    输入输出格式

    输入格式:

    第一行,三个整数N、M、K。

    第二行,N个整数,表示小B的序列。

    接下来的M行,每行两个整数L、R。

    输出格式:

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

    输入输出样例

    输入样例#1:
    6 4 3
    1 3 2 1 1 3
    1 4
    2 6
    3 5
    5 6
    输出样例#1:
    6
    9
    5
    2

    说明

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

    裸莫队。

    对于求平方可以先减去,再加回来‘

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<cmath>
     5 #include<algorithm>
     6 using namespace std;
     7 const int MAXN=50001;
     8 void read(int & n)
     9 {
    10     char c='+';int x=0;bool flag=0;
    11     while(c<'0'||c>'9')
    12     {c=getchar();if(c=='-')flag=1;}
    13     while(c>='0'&&c<='9')
    14     {x=x*10+(c-48);c=getchar();}
    15     flag==1?n=-x:n=x;
    16 }
    17 int n,m,k,base;
    18 struct node
    19 {
    20     int l,r,id;
    21 }q[MAXN];
    22 int ans=0;
    23 int pos[MAXN],a[MAXN],out[MAXN];
    24 int comp(const node & a,const node & b)
    25 {
    26     if(pos[a.l]==pos[b.l])
    27         return a.r<b.r;
    28     else 
    29         return pos[a.l]<pos[b.l];
    30 }
    31 int happen[MAXN];// 记录区间内每一个数的出现次数 
    32 void add(int p)
    33 {
    34     if(p<=k)
    35     {
    36         ans-=happen[p]*happen[p];
    37         happen[p]++;
    38         ans+=happen[p]*happen[p];
    39     }
    40 }
    41 void dele(int p)
    42 {
    43     if(p<=k)
    44     {
    45         ans-=happen[p]*happen[p];
    46         happen[p]--;
    47         ans+=happen[p]*happen[p];
    48     }
    49 }
    50 void modui()
    51 {
    52     int ll=1,rr=0;
    53     for(int i=1;i<=m;i++)
    54     {
    55         for(;q[i].l<ll;ll--)
    56             add(a[ll-1]);
    57         for(;q[i].l>ll;ll++)
    58             dele(a[ll]);
    59         for(;q[i].r<rr;rr--)
    60             dele(a[rr]);
    61         for(;q[i].r>rr;rr++)
    62             add(a[rr+1]);
    63         out[q[i].id]=ans;
    64     }
    65     for(int i=1;i<=m;i++)
    66         printf("%d
    ",out[i]);
    67 }
    68 int main()
    69 {
    70     read(n);read(m);read(k);
    71     for(int i=1;i<=n;i++)
    72         read(a[i]);
    73     base=sqrt(n);
    74     for(int i=1;i<=n;i++)
    75         pos[i]=(i-1)/base+1;
    76     for(int i=1;i<=m;i++)
    77     {
    78         int x,y;
    79         read(x);read(y);
    80         q[i].l=x;q[i].r=y;q[i].id=i;
    81     }
    82     sort(q+1,q+m+1,comp);
    83     modui();
    84     return 0;
    85 }
  • 相关阅读:
    Visual Studio 正则表达式替换
    NHibernate MappingException. No Persister
    C#枚举
    测试
    NHibernate & INotifyPropertyChanged
    NHibernate Profiler使用方法
    根据条件动态拼接LinQ的where条件字串
    wpf中ToolTip实现
    jquery的colorbox关闭并传递数据到父窗
    c#简易反射调用泛型方法
  • 原文地址:https://www.cnblogs.com/zwfymqz/p/7086926.html
Copyright © 2020-2023  润新知