JOISC2014C 歴史の研究
Link
回滚莫队板子。
#pragma GCC optimize(3)
#include<cmath>
#include<cstdio>
#include<cctype>
#include<algorithm>
using std::lower_bound;
using std::sort;
using std::unique;
using ll=long long;
namespace IO
{
char ibuf[(1<<21)+1],obuf[(1<<21)+1],st[17],*iS,*iT,*oS=obuf,*oT=obuf+(1<<21);
char Get(){return (iS==iT? (iT=(iS=ibuf)+fread(ibuf,1,(1<<21)+1,stdin),(iS==iT? EOF:*iS++)):*iS++);}
void Flush(){fwrite(obuf,1,oS-obuf,stdout),oS=obuf;}
void Put(char x){*oS++=x;if(oS==oT)Flush();}
int read(){int x=0,c=Get();while(!isdigit(c))c=Get();while(isdigit(c))x=x*10+c-48,c=Get();return x;}
void write(ll x){int top=0;while(x)st[++top]=(x%10)+48,x/=10;while(top)Put(st[top--]);Put('\n');}
}using IO::read;using IO::write;using IO::Flush;
int min(int a,int b){return a<b? a:b;}
ll max(ll a,ll b){return a>b? a:b;}
const int N=100007;
int n,m,Q,a[N],h[N],bel[N],stk[N],t[N];ll ans[N];
struct node{int l,r,id;}q[N];
int operator<(node a,node b){return bel[a.l]<bel[b.l]||(bel[a.l]==bel[b.l]&&a.r<b.r);}
ll calc(int l,int r)
{
ll ans=0;
for(int i=l;i<=r;++i) ++t[a[i]],ans=max(ans,1ll*h[a[i]]*t[a[i]]);
for(int i=l;i<=r;++i) t[a[i]]=0;
return ans;
}
int main()
{
n=read(),Q=read();int B=sqrt(n)+(rand()&7),S=(n-1)/B+1;
for(int i=1;i<=n;++i) bel[i]=(i-1)/B+1,a[i]=h[i]=read();
sort(h+1,h+n+1),m=unique(h+1,h+n+1)-h-1;
for(int i=1;i<=n;++i) a[i]=lower_bound(h+1,h+m+1,a[i])-h;
for(int i=1;i<=Q;++i) q[i]={read(),read(),i};
sort(q+1,q+Q+1);
for(int p=1,i=1;i<=S;++i)
{
int lim=min(n,i*B),l=lim+1,r=lim,top=0;
ll mx=0,tmp;
for(;bel[q[p].l]==i;++p)
{
if(bel[q[p].r]==i) {ans[q[p].id]=calc(q[p].l,q[p].r);continue;}
for(;r<q[p].r;mx=max(mx,1ll*h[a[r]]*t[a[r]])) if(++t[a[++r]],t[a[r]]==1) stk[++top]=a[r];
tmp=mx;
for(;l>q[p].l;) ++t[a[--l]],mx=max(mx,1ll*h[a[l]]*t[a[l]]);
ans[q[p].id]=mx,mx=tmp;
for(;l<=lim;++l) --t[a[l]];
}
for(int i=1;i<=top;++i) t[stk[i]]=0;
}
for(int i=1;i<=Q;++i) write(ans[i]);
return Flush(),0;
}