离线算法-莫队
Gaoxing233 · · 算法·理论
普通莫队
莫队算法将询问离线分块后排序,通过双指针更新序列状态,从而达到
要求
通过一个状态
实现
通常令块长
对于每组询问,以
请注意
时间复杂度分析
设序列长度为
按
关注
关注
综上,莫队的时间复杂度为
若令
代码实现,以P1494为例
#include <bits/stdc++.h>
#define pr pair<int,int>
#define ft first
#define sd second
using namespace std;
using llt=long long;
const int maxn=5e4+5,B=sqrt(maxn);
int n,m,a[maxn];
llt cnt[maxn],tans;
struct Q
{
int l,r,id;
};
Q q[maxn];
pr ans[maxn];
bool operator < (const Q &x,const Q &y)
{
if(x.l/B==y.l/B) return x.r<y.r;
return x.l/B<y.l/B;
}
llt gcd(llt x,llt y)
{
if(y==0) return x;
return gcd(y,x%y);
}
void srt(pr &x)
{
llt t=gcd(x.sd,x.ft);
x.ft/=t;
x.sd/=t;
}
void update(int x,int f)//更新函数
{
tans-=cnt[x]*(cnt[x]-1)/2;
cnt[x]+=f;
tans+=cnt[x]*(cnt[x]-1)/2;
}
int main()
{
// freopen("test.in","r",stdin);
// freopen("test.out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=m;i++)
{
cin>>q[i].l>>q[i].r;
q[i].id=i;
}
sort(q+1,q+m+1);
int l=1,r=0;
for(int i=1;i<=m;i++)//核心代码
{
while(l<q[i].l) update(a[l++],-1);
while(l>q[i].l) update(a[--l],1);
while(r<q[i].r) update(a[++r],1);
while(r>q[i].r) update(a[r--],-1);
ans[q[i].id]={tans,1ll*(q[i].r-q[i].l+1)*(q[i].r-q[i].l)/2};
if(tans==0) ans[q[i].id].sd=1;
srt(ans[q[i].id]);
}
for(int i=1;i<=m;i++) cout<<ans[i].ft<<"/"<<ans[i].sd<<"\n";
return 0;//I love 514.
}
带修改莫队
普通的莫队算法只支持查询操作。带修改莫队通过引入修改时间实现对莫队的修改,从而到达
要求
通过一个状态
实现
与普通莫队不同,通常令块长
对于每组询问,以
请再次注意
时间复杂度分析&块长的推导
前置知识:均值不等式/基本不等式
设序列长度为
设块长为
设
可知,对于每组左右端点不换块的询问,移动次数为
则总操作次数为:
当且仅当
综上,时间复杂度为
若
代码实现,以P1903为例
#include <bits/stdc++.h>
using namespace std;
const int maxn=133333+5,B=pow(maxn,0.66),maxm=1e6+5;
int n,m,a[maxn],cnt[maxm],tans,ans[maxn],tot;
bool vis[maxn];
struct ask
{
int l,r,d;
};
ask q[maxn];
vector<ask> g;
bool operator < (const ask &x,const ask &y)
{
if(x.l/B==y.l/B&&x.r/B==y.r/B) return x.d<y.d;
if(x.l/B==y.l/B) return x.r/B<y.r/B;
return x.l/B<y.l/B;
}
void update(int x,int f)
{
if(cnt[x]==1&&f==-1) tans--;
if(cnt[x]==0&&f==1) tans++;
cnt[x]+=f;
}
int main()
{
// freopen("test.in","r",stdin);
// freopen("test.out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=m;i++)
{
char p;
cin>>p>>q[tot+1].l>>q[tot+1].r;
q[tot+1].d=i;
if(p=='Q')
{
vis[i]=true;
tot++;
}
else
{
g.push_back(q[tot+1]);
}
}
sort(q+1,q+tot+1);
int l=1,r=0,pos=0;
for(int i=1;i<=tot;i++)
{
while(l<q[i].l) update(a[l++],-1);
while(l>q[i].l) update(a[--l],1);
while(r<q[i].r) update(a[++r],1);
while(r>q[i].r) update(a[r--],-1);
while(pos<g.size()&&g[pos].d<q[i].d)//对时间轴的更新
{
if(l<=g[pos].l&&g[pos].l<=r)
{
update(a[g[pos].l],-1);
update(g[pos].r,1);
}
swap(g[pos].r,a[g[pos].l]);
pos++;
}
while(pos-1>=0&&g[pos-1].d>q[i].d)
{
if(l<=g[pos-1].l&&g[pos-1].l<=r)
{
update(a[g[pos-1].l],-1);
update(g[pos-1].r,1);
}
swap(g[pos-1].r,a[g[pos-1].l]);
pos--;
}
ans[q[i].d]=tans;
}
for(int i=1;i<=m;i++)
{
if(vis[i]) cout<<ans[i]<<"\n";
}
return 0;//I love 514.
}