【莫队算法】BZOJ2038 [2009国家集训队]小Z的袜子

本文介绍了一道经典的莫队算法题目,详细解释了如何利用该算法求解区间[L,R]的问题,并给出了具体的代码实现。文章重点在于如何通过维护分子简化分数计算过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题面在这里

莫队的经典题……
对于已知区间[L,R],它的答案是:

C2c[i]C2RL+1

由于处理分数比较麻烦,所以我们只要维护分子即可
即:对于变化的c[i]个数(设为x),维护 C2x
减去原来的,加上后面的即可

附上代码:

#include<cstdio>
#include<algorithm>
#include<cmath>
#define LL long long
using namespace std;
const int maxn=50005;
int n,q,a[maxn],h[maxn],hsh[maxn];
LL now;
LL c2(int x) {return (LL)x*(x-1)/2;}
LL gcd(LL x,LL y){
    if (y==0) return x;
    return gcd(y,x%y);
}
struct data{
    int l,r,id;
    bool operator<(const data&b)const{
        if (h[l]==h[b.l]) return r<b.r;
        return l<b.l;
    }
}que[maxn];
struct la{
    LL x,y;
}ans[maxn];
inline int red(){
    int tot=0,f=1;char ch=getchar();
    while (ch<'0'||'9'<ch) {if (ch=='-') f=-f;ch=getchar();}
    while ('0'<=ch&&ch<='9') tot=tot*10+ch-48,ch=getchar();
    return f*tot;
}
void blocker(){
    int k=sqrt(n);
    for (int i=1;i<=n;i++) h[i]=(i-1)/k+1;
}
void update(int x,int d){
    now-=c2(hsh[a[x]]);
    hsh[a[x]]+=d;
    now+=c2(hsh[a[x]]);
}
int main(){
    n=red(),q=red();
    for (int i=1;i<=n;i++) a[i]=red();
    blocker();
    for (int i=1;i<=q;i++) que[i].l=red(),que[i].r=red(),que[i].id=i;
    sort(que+1,que+1+q);
    update(1,1);
    for (int i=1,L=1,R=1;i<=q;i++){
        while (L<que[i].l) update(L++,-1);
        while (L>que[i].l) update(--L,1);
        while (R<que[i].r) update(++R,1);
        while (R>que[i].r) update(R--,-1);
        ans[que[i].id]=(la){now,c2(que[i].r-que[i].l+1)};
    }
    for (int i=1;i<=q;i++){
        LL t=gcd(ans[i].x,ans[i].y);
        ans[i].x/=t;ans[i].y/=t;
        if (ans[i].x==0) printf("0/1\n");else printf("%lld/%lld\n",ans[i].x,ans[i].y);
    }
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值