[BZOJ 3781] 小B的询问

[题目链接]

         https://www.lydsy.com/JudgeOnline/problem.php?id=3781

[算法]

        莫队算法

[代码]

       

#include<bits/stdc++.h>
using namespace std;
#define MAXN 50010
typedef long long ll;

int i,n,m,k,l,r,len;
int a[MAXN],c[MAXN],block[MAXN];
ll sum;
ll ans[MAXN];

struct Query
{
    int l,r,id;
} q[MAXN];

inline bool cmp(Query a,Query b)
{
    if (block[a.l] == block[b.l]) return a.r < b.r;
    else return a.l < b.l;
}
inline void add(int pos)
{
    sum -= c[a[pos]] * c[a[pos]];
    c[a[pos]]++;
    sum += c[a[pos]] * c[a[pos]];    
}
inline void dec(int pos)
{
    sum -= c[a[pos]] * c[a[pos]];
    c[a[pos]]--;
    sum += c[a[pos]] * c[a[pos]];
}

int main()
{
    
    scanf("%d%d%d",&n,&m,&k);
    len = sqrt(n);
    for (i = 1; i <= n; i++) block[i] = (i - 1) / len + 1;
    for (i = 1; i <= n; i++) scanf("%d",&a[i]);
    for (i = 1; i <= m; i++)
    {
        scanf("%d%d",&q[i].l,&q[i].r);
        q[i].id = i;
    }
    sort(q+1,q+m+1,cmp);
    l = q[1].l; r = q[1].l - 1;
    for (i = 1; i <= m; i++)
    {
        while (r < q[i].r)
        {
            add(r+1);
            r++;
        }
        while (r > q[i].r)
        {
            dec(r);
            r--;
        }
        while (l < q[i].l)
        {
            dec(l);
            l++;
        }
        while (l > q[i].l)
        {
            add(l-1);
            l--;
        }
        ans[q[i].id] = sum;
    }
    for (i = 1; i <= m; i++) printf("%lld\n",ans[i]);

    return 0;
}

 

posted @ 2018-07-17 11:08  evenbao  阅读(139)  评论(0编辑  收藏  举报