3781: 小B的询问
Time Limit: 10 Sec Memory Limit: 128 MB[ Submit][ Status][ Discuss]
Description
小B有一个序列,包含N个1~K之间的整数。他一共有M个询问,每个询问给定一个区间[L..R],求Sigma(c(i)^2)的值,其中i的值从1到K,其中c(i)表示数字i在[L..R]中的重复次数。小B请你帮助他回答询问。
Input
第一行,三个整数N、M、K。
第二行,N个整数,表示小B的序列。
接下来的M行,每行两个整数L、R。
Output
M行,每行一个整数,其中第i行的整数表示第i个询问的答案。
Sample Input
6 4 3
1 3 2 1 1 3
1 4
2 6
3 5
5 6
1 3 2 1 1 3
1 4
2 6
3 5
5 6
Sample Output
6
9
5
2
9
5
2
HINT
对于全部的数据,1<=N、M、K<=50000
Source
不想说了,要多水有多水
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
typedef long long ll;
const int N = 50000 + 5;
int n,m,k,cnt[N],a[N];
struct data{
int l,r,id,block;
}e[N];
ll c[N],Ans[N];
bool cmp( data a, data b ){
if( a.block == b.block ) return a.r < b.r;
return a.block < b.block;
}
void capmo(){
int l = 1, r = 0; ll ans = 0;
for( int i = 1; i <= m; i++ ){
while( l > e[i].l ){ l--; cnt[a[l]]++; ans += 2*cnt[a[l]]-1; }
while( r < e[i].r ){ r++; cnt[a[r]]++; ans += 2*cnt[a[r]]-1; }
while( l < e[i].l ){ cnt[a[l]]--; ans -= 2*cnt[a[l]]+1; l++; }
while( r > e[i].r ){ cnt[a[r]]--; ans -= 2*cnt[a[r]]+1; r--; }
Ans[e[i].id] = ans;
}
}
int main(){
scanf("%d%d%d", &n, &m, &k);
for( int i = 1; i <= n; i++ ) scanf("%d", &a[i]);
int size = sqrt(n);
for( int i = 1; i <= m; i++ ){
scanf("%d%d", &e[i].l, &e[i].r );
e[i].id = i; e[i].block = (e[i].l-1)/size;
}
std::sort(e+1,e+m+1,cmp);
capmo();
for( int i = 1; i <= m; i++ ) printf("%lld\n",Ans[i]);
return 0;
}