莫队算法

· · 个人记录

P2709

#include <bits/stdc++.h>
#define MAXN 50010

using namespace std;

int n , m , k , B , a[ MAXN ];
long long ans , res[ MAXN ] , cnt[ MAXN ];

struct query
{
    int l , r , t;
    //询问区间的l,r,这个是第t次询问 
} q[ MAXN ];

bool cmp( query a , query b )
{
    //先按照a,b左端点所在块的编号比较
    if( a.l / B != b.l / B )
        return a.l / B < b.l / B;
    //再按照a,b右端点比较 
    return a.r < b.r;
}

void erase( int x )
{
    //删除x并且更新答案
    ans -= cnt[x] * cnt[x];
    cnt[x]--;
    ans += cnt[x] * cnt[x]; 
}

void insert( int x )
{
    //加入x并且更新答案
    ans -= cnt[x] * cnt[x];
    cnt[x]++;
    ans += cnt[x] * cnt[x]; 
}

int main()
{
    cin >> n >> m >> k;
    B = n / ( sqrt( m ) + 1 );
    for( int i = 1 ; i <= n ; i++ )
        cin >> a[i];
    for( int i = 1 ; i <= m ; i++ )
    {
        cin >> q[i].l >> q[i].r;
        q[i].t = i;
    }
    sort( q + 1 , q + m + 1 , cmp );
    int l = 1 , r = 0;
    for( int i = 1 ; i <= m ; i++ )
    {
        while( l > q[i].l )
        {
            l--;
            insert( a[l] );
        }
        while( r < q[i].r )
        {
            r++;
            insert( a[r] );
        }
        while( l < q[i].l )
        {
            erase( a[l] );
            l++;
        }
        while( r > q[i].r )
        {
            erase( a[r] );
            r--;
        }
        res[ q[i].t ] = ans;
    }
    for( int i = 1 ; i <= m ; i++ )
        cout << res[i] << endl;
    return 0;
}