zoukankan      html  css  js  c++  java
  • luoguP2709 小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

    分析:莫队

    这里写代码片
    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<algorithm>
    #include<cmath>
    
    using namespace std;
    
    int n,m,k;
    int p[50020];
    struct node{
        int x,y,id,block;
    };
    node ask[50020];
    int ans[50020],a[50010];
    int unit;
    
    int cmp(const node &a,const node &b)
    {
        if (a.block!=b.block) return a.block<b.block;
        else return a.y<b.y;
    }
    
    void doit()
    {
        int L=1;
        int R=0;
        int tmp=0;
        int i;
        for (i=1;i<=m;i++)
        {
            while (R<ask[i].y)
            {
                R++;
                p[a[R]]++;
                tmp+=(p[a[R]]*2-1);
            }
            while (R>ask[i].y)
            {
                p[a[R]]--;
                tmp-=(p[a[R]]*2+1);
                R--;
            }
            while (L<ask[i].x)
            {
                p[a[L]]--;
                tmp-=(p[a[L]]*2+1);
                L++;
            }
            while (L>ask[i].x)
            {
                L--;
                p[a[L]]++;
                tmp+=(p[a[L]]*2-1);
           }
            ans[ask[i].id]=tmp;
        }   
    }
    
    int main()
    {
        scanf("%d%d%d",&n,&m,&k);
        for (int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        unit=(int)sqrt(n);
        for (int i=1;i<=m;i++)
        {
            scanf("%d%d",&ask[i].x,&ask[i].y);
            ask[i].id=i;
            ask[i].block=(ask[i].x-1)/unit+1;
        }
        sort(ask+1,ask+1+m,cmp);
        doit();
        for (int i=1;i<=m;i++)
           printf("%d
    ",ans[i]);   
        return 0;
    }
  • 相关阅读:
    20191017-1 每周例行报告
    20191010-2 每周例行报告
    20190919-1 每周例行报告
    彭思雨20190919-3效能分析
    zipfile
    subprocess
    configparser
    hashlib
    json & pickle
    headpq
  • 原文地址:https://www.cnblogs.com/wutongtong3117/p/7673266.html
Copyright © 2011-2022 走看看