模板代码——莫队

· · 算法·理论

普通莫队:

#include<bits/stdc++.h>
#define ll long long
#define rep(i,x,y) for(int i=x;i<=y;i++) 
using namespace std;
const int N=1e5+5;

int n,m,k,a[N],B;
ll c[N],cur,ans[N];
struct node
{
    int id,l,r;
    bool operator<(const node &cmp)const//分块 
    {
        if(l/B!=cmp.l/B) return l<cmp.l;//如果不在一个块里,按左端点升序排序 
        if(l/B&1) return r<cmp.r;//否则如果在一个块里,进行奇偶化排序:奇增偶减,常数优化 
        return r>cmp.r;
    }
}b[N];
void update(int i,int opt)//区间端点移动的修改函数 
{
    cur-=c[a[i]]*c[a[i]];
    c[a[i]]+=opt;//opt为1代表加点,为-1代表删点 
    cur+=c[a[i]]*c[a[i]];
}
int main()
{
    cin>>n>>m>>k;
    B=sqrt(n);
    rep(i,1,n) cin>>a[i];
    rep(i,1,m) cin>>b[i].l>>b[i].r,b[i].id=i;
    sort(b+1,b+1+m);
    int l=1,r=0;//初始化左右端点,注意l为1且r从0开始往右扫,才能初始化出第一个区间 
    rep(i,1,m)//O(n sqrt(n))
    {
        //先加点后删点 
        while(l>b[i].l) update(--l,1);
        while(r<b[i].r) update(++r,1);
        while(l<b[i].l) update(l++,-1);
        while(r>b[i].r) update(r--,-1);
        ans[b[i].id]=cur;//保存答案 
    }
    rep(i,1,m) cout<<ans[i]<<endl;
    return 0;
}

带修莫队:

#include<bits/stdc++.h>
#define ll long long
#define rep(i,x,y) for(int i=x;i<=y;i++)
using namespace std;
const int N=1.5e5+5,M=1e6+5;

int n,m,B,cur,a[N],cnt[M],ans[N];
int qcnt,ocnt;
struct node
{
    int l,r,t,id;
    bool operator<(const node &cmp)const
    {
        if(l/B!=cmp.l/B) return l<cmp.l;
        if(r/B!=cmp.r/B) return r<cmp.r;
        return t<cmp.t;//左端点在同一块,右端点也在同一块,则按查询时间排序 
    }
}q[N];
struct operation 
{
    int p,c;
}op[N];
void add(int i)
{
    if(!cnt[i]++) cur++;
}
void del(int i)
{
    if(!--cnt[i]) cur--;
}
int main()
{
    cin>>n>>m;
    B=pow(n,2.0/3);
    rep(i,1,n) cin>>a[i];
    rep(i,1,m)
    {
        char opt;
        int l,r;
        cin>>opt>>l>>r;
        if(opt=='Q') q[++qcnt]={l,r,ocnt,qcnt};
        else op[++ocnt]={l,r};
    }
    sort(q+1,q+1+qcnt);
    int l=1,r=0,lst=0;
    rep(i,1,qcnt)
    {
        while(l>q[i].l) add(a[--l]);
        while(r<q[i].r) add(a[++r]);
        while(l<q[i].l) del(a[l++]);
        while(r>q[i].r) del(a[r--]);
        while(lst<q[i].t)//修改操作 
        {
            lst++;
            if(l<=op[lst].p&&op[lst].p<=r)
                add(op[lst].c),del(a[op[lst].p]);
            swap(op[lst].c,a[op[lst].p]);//交换以便之后进行还原操作 
        }
        while(lst>q[i].t)//还原操作 
        {
            if(l<=op[lst].p&&op[lst].p<=r)
                add(op[lst].c),del(a[op[lst].p]);
            swap(op[lst].c,a[op[lst].p]);//交换回原修改操作的信息 
            lst--;
        }
        ans[q[i].id]=cur;
    }
    rep(i,1,qcnt) cout<<ans[i]<<endl;
    return 0;
}