bzoj4241 历史研究
原题地址:http://www.lydsy.com/JudgeOnline/problem.php?id=4241
题意:
日记中记录了连续N天发生的时间,大约每天发生一件。
事件有种类之分。第i天(1<=i<=N)发生的事件的种类用一个整数Xi表示,Xi越大,事件的规模就越大。
JOI教授决定用如下的方法分析这些日记:
1. 选择日记中连续的一些天作为分析的时间段
2. 事件种类t的重要度为t*(这段时间内重要度为t的事件数)
3. 计算出所有事件种类的重要度,输出其中的最大值
每次给出分析的区间,你需要输出重要度的最大值。
数据范围
1<=N<=10^5
1<=Q<=10^5
1<=Xi<=10^9 (1<=i<=N)
题解:
回滚莫队,原来是这么个玩意。
同样按左端点所在块和右端点排序。
对于左右端点在同一块的,暴力统计,sqrt(n)每次。
对于左右端点不在同一块的,
这些中左端点所在块相同的,是一段连续的区间,而对于这些询问右端点递增。
那么从左端点所在块下一块结开头统计到右端点为止,这个右指针是递增的。
剩下的部分每次从左指针统计到左端点所在块结束,也是sqrt(n)每次。
时间复杂度 O(n sqrt(n))
代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#define LL long long
using namespace std;
const int N=100005;
int n,m,val[N],num[N],a[N],blo[N],st[N],ed[N],B,cnt[N],bcnt[N];
LL ans[N],cur=0;
struct Query
{
int L,R,id;
}Q[N];
void init()
{
B=sqrt(n);
for(int i=1;i<=n;i++)
{
blo[i]=(i-1)/B+1;
if(i==1) st[blo[i]]=i;
else if(blo[i]!=blo[i-1]) {st[blo[i]]=i; ed[blo[i-1]]=i-1;}
}
for(int i=1;i<=n;i++) { scanf("%d",&val[i]); a[i]=val[i];}
sort(a+1,a+n+1); int tot=unique(a+1,a+n+1)-a-1;
for(int i=1;i<=n;i++) num[i]=lower_bound(a+1,a+tot+1,val[i])-a;
}
bool cmp(const Query &A,const Query &B)
{
return (blo[A.L]!=blo[B.L])? A.L<B.L : A.R<B.R;
}
void moto()
{
int lastB=0,rg=0;
for(int i=1;i<=m;i++)
{
if(blo[Q[i].L]==blo[Q[i].R])
{
cur=0;
for(int j=Q[i].L;j<=Q[i].R;j++)
{bcnt[num[j]]++; cur=max(cur,1LL*a[num[j]]*bcnt[num[j]]);}
ans[Q[i].id]=cur;
for(int j=Q[i].L;j<=Q[i].R;j++) bcnt[num[j]]--;
}
else
{
if(blo[Q[i].L]!=lastB)
{
memset(cnt,0,sizeof(cnt));
rg=ed[blo[Q[i].L]]; cur=0; lastB=blo[Q[i].L];
}
while(rg<Q[i].R) {rg++; cnt[num[rg]]++; cur=max(cur,1LL*a[num[rg]]*cnt[num[rg]]);}
LL now=cur;
for(int lf=ed[blo[Q[i].L]];lf>=Q[i].L;lf--)
{ cnt[num[lf]]++; now=max(now,1LL*a[num[lf]]*cnt[num[lf]]);}
for(int lf=ed[blo[Q[i].L]];lf>=Q[i].L;lf--) cnt[num[lf]]--;
ans[Q[i].id]=now;
}
}
}
int main()
{
scanf("%d%d",&n,&m);
init();
for(int i=1;i<=m;i++) {scanf("%d%d",&Q[i].L,&Q[i].R); Q[i].id=i;}
sort(Q+1,Q+m+1,cmp);
moto();
for(int i=1;i<=m;i++) printf("%lld\n",ans[i]);
return 0;
}