题目
思路
回滚莫队的板子。
代码
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
# define FOR(i,a,b) for(int i=(a); i<=(b); ++i)
inline int readint(){
int a; scanf("%d",&a); return a;
}
const int MaxN = 100005, SqrtN = 342;
int n, q;
struct Query{
int l, r, id;
void input(){
l = readint(), r = readint();
}
bool operator<(const Query &that)const{
if(l/SqrtN != that.l/SqrtN)
return l/SqrtN > that.l/SqrtN;
else return r < that.r;
}
} query[MaxN];
int val[MaxN], b[MaxN];
void input(){
n = readint(), q = readint();
for(int i=1; i<=n; ++i)
b[i] = val[i] = readint();
for(int i=1; i<=q; ++i)
query[i].input(), query[i].id = i;
sort(b+1,b+n+1), sort(query+1,query+q+1);
for(int i=1,*endpos=unique(b+1,b+n+1); i<=n; ++i)
val[i] = lower_bound(b+1,endpos,val[i])-b;
}
int cnt[MaxN]; long long ans;
void add(int i,int f){
cnt[val[i]] += f; // +1 or -1
ans = max(ans,1ll*b[val[i]]*cnt[val[i]]);
}
long long realAns[MaxN];
void solve(){
FOR(qid,1,q) if(query[qid].l/SqrtN == query[qid].r/SqrtN){
FOR(i,query[qid].l,query[qid].r) add(i,1);
realAns[query[qid].id] = ans;
FOR(i,query[qid].l,query[qid].r) add(i,-1);
ans = 0; // release
}
for(int qid=1,l=n+1,r=n; qid<=q; ++qid){
while(qid <= q and query[qid].l/SqrtN == query[qid].r/SqrtN)
++ qid; // 已经处理过了
if(qid > q) break; // over
int bound = (query[qid].l/SqrtN+1)*SqrtN;
if(bound > n) bound = n+1;
if(l != bound){
l = bound, r = l-1;
FOR(i,1,n) cnt[i] = 0;
ans = 0; // 清零
}
while(r < query[qid].r) add(++r,1);
long long nowAns = ans;
while(query[qid].l < l) add(--l,1);
realAns[query[qid].id] = ans;
while(l < bound) add(l++,-1);
ans = nowAns; // release
}
for(int i=1; i<=q; ++i)
printf("%lld\n",realAns[i]);
}
int main(){
input(), solve();
return 0;
}