您的位置:首页 > 其它

莫队算法 小Z的袜子

2016-02-19 13:17 316 查看
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<cmath>
#include<string>
#include<algorithm>
#include<set>
#include<map>
#include<cstring>
#include<queue>
#include<stack>
#include<list>

using namespace std;

typedef long long ll;
const int MAXN=50010;

struct Query{
int L,R,id;
}node[MAXN];

ll gcd(ll a,ll b){
if(b==0)return a;
return gcd(b,a%b);
}

struct Ans{
ll a,b;
void reduce(){
ll d=gcd(a,b);
a/=d;b/=d;
}
}ans[MAXN];

int a[MAXN];
int num[MAXN];
int n,m,unite;

bool cmp( Query a,Query b ){
if(a.L/unite==b.L/unite)return a.R<b.R;
return a.L/unite<b.L/unite;
}

ll pow2(ll x){
return x*x;
}

void work(){
ll tmp=0;
memset(num,0,sizeof(num));
int L=1;
int R=0;
for(int i=0;i<m;i++){
while( R<node[i].R ){
R++;
tmp-= pow2( num[a[R]] );
num[ a[R] ]++;
tmp+= pow2( num[a[R]] );
}
while( R>node[i].R ){
tmp-= pow2( num[a[R]] );
num[ a[R] ]--;
tmp+= pow2( num[a[R]] );
R--;
}
while( L<node[i].L ){
tmp-= pow2( num[a[L]] );
num[ a[L] ]--;
tmp+= pow2( num[a[L]] );
L++;
}
while( L>node[i].L ){
L--;
tmp-= pow2( num[a[L]] );
num[ a[L] ]++;
tmp+= pow2( num[a[L]] );
}
ans[ node[i].id ].a=tmp-(R-L+1);
ans[ node[i].id ].b=(ll) (R-L+1)*(R-L);
ans[ node[i].id ].reduce();

}

}

int main()
{
while(scanf("%d%d",&n,&m)!=EOF){
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
for(int i=0;i<m;i++){
node[i].id=i;
scanf("%d%d",&node[i].L,&node[i].R);
}
unite=(int ) sqrt(n);
sort( node,node+m,cmp );
work();
for(int i=0;i<m;i++){
printf("%lld/%lld\n",ans[i].a,ans[i].b);
}

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: