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

    #include<bits/stdc++.h>
    using namespace std ;
    #define N 50005
    #define ll long long
    
    inline int read()
    {
        int f=1,x=0 ; char ch;
        do{ch=getchar() ; if(ch=='-')f=-1;} while(ch<'0' || ch>'9') ;
        do{x=x*10+ch-'0' ; ch=getchar() ; } while(ch>='0'&&ch<='9') ;
        return x*f;
    }
    
    struct Query
    {
        int l,r,id,pos;
        bool operator <(const Query &x) const
        {
            if(pos==x.pos)
            return r<x.r;
            else
            return pos<x.pos;
        }
    }a[N];
    int b[N],n,m,K ; ll cnt[N],Ans[N];
    int main()
    {
        n=read() ; m=read() ; K=read() ;
        int size=(int)sqrt(n);///分块
        for(int i=1 ; i<=n ; i++)
        b[i]=read();
    
        for(int i=1 ; i<=m ; i++)
        {
            a[i].l=read() ; a[i].r=read() ; a[i].id=i;
            a[i].pos=(a[i].l-1)/size+1; ///位置
        }
        sort(a+1,a+1+m);
        int l=1,r=0; ll ans=0;
        for(int i=1 ; i<=m ; i++)
        {
            while(l>a[i].l) l-- , cnt[b[l]]++ , ans+=2*cnt[b[l]]-1;
            while(r<a[i].r) r++ , cnt[b[r]]++ , ans+=2*cnt[b[r]]-1;
            while(l<a[i].l) cnt[b[l]]-- , ans-=2*cnt[b[l]]+1 , l++;
            while(r>a[i].r) cnt[b[r]]-- , ans-=2*cnt[b[r]]+1 , r--;
            Ans[a[i].id]=ans;
        }
        for(int i=1 ; i<=m ; i++)
        printf("%lld
    ",Ans[i]);
        return 0;
    }
    View Code
  • 相关阅读:
    hdu2818 Building Block
    struct2面试准备
    Spring mvc 面试
    Spring 面试详解
    Java面试必备Springioc上
    redis高级命令4 持久化机制 、事务
    redis高级命令3哨兵模式
    redis高级命令2
    redis高级命令1
    redis基础二----操作set数据类型
  • 原文地址:https://www.cnblogs.com/shuaihui520/p/10286935.html
Copyright © 2011-2022 走看看