莫队模板题 小Z的袜子

离线的经典算法
先分块 然后按左端点所在的块先后顺序排序 再按右端点排序
L和R一直移动就好 不知道为什么感觉莫队就是优化+暴力
复杂度O(n^2)降到O(n^1.5)
分了个块也就排序用用o(╯□╰)o 之后就用不着了 很神奇的算法 表示已经被折服了

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<queue>
#include<vector>
#define M 50005
#define ll long long
using namespace std;
struct node{
    int l,r,id;
    ll ans,sum;
}Q[M];
ll ans;
int n,m,block[M],A[M];
ll cnt[M];
bool cmp(node a,node b){
    if(block[a.l]!=block[b.l])return block[a.l]<block[b.l];
    return a.r<b.r;
}
bool cmp1(node a,node b){
    return a.id<b.id;
}
void Rd(int &res){
    char c;res=0;
    while(c=getchar(),!isdigit(c));
    do res=(res<<1)+(res<<3)+(c^48);
    while(c=getchar(),isdigit(c));
}
ll gcd(ll n,ll m){
    if(m==0)return n;
    else return gcd(m,n%m);
}
void init(){
    Rd(n);Rd(m);
    int limit=sqrt(n);
    for(int i=1;i<=n;i++){
        Rd(A[i]);
        block[i]=(i-1)/limit+1;
        cnt[A[i]]++;
        ans+=cnt[A[i]]-1;
    }
    for(int i=1;i<=m;i++){
        Rd(Q[i].l);Rd(Q[i].r);
        Q[i].id=i;
        Q[i].sum=1LL*(Q[i].r-Q[i].l+1)*(Q[i].r-Q[i].l)/2;
    }
    sort(Q+1,Q+m+1,cmp);
}
void update(ll x,ll y){
    ans-=1ll*cnt[A[x]]*(cnt[A[x]]-1)/2;
    cnt[A[x]]+=y;
    ans+=1ll*cnt[A[x]]*(cnt[A[x]]-1)/2;
}
void solve(){
    ll l=1,r=n;
    for(int i=1;i<=m;i++){
        while(l<Q[i].l){
            update(l,-1);
            l++;
        }
        while(l>Q[i].l){
            update(l-1,1);
            l--;
        }
        while(r<Q[i].r){
            update(r+1,1);
            r++;
        }
        while(r>Q[i].r){
            update(r,-1);
            r--;
        }
        Q[i].ans=ans;
    }
    sort(Q+1,Q+m+1,cmp1);
    for(int i=1;i<=m;i++){
        ll GCD=gcd(Q[i].sum,Q[i].ans);
        printf("%lld/%lld\n",Q[i].ans/GCD,Q[i].sum/GCD);
        //不知道为什么不能用cout  RE无数次  一口老血喷了出
    }
}
int main(){
    init();
    solve();
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值