题目大意
定义一个长度为
m
序列
现有一个长度为
n
的序列
Data Constraint
n,q≤5∗105
题解
如果是暴力,我们显然可以用一个单调栈求每个数的贡献计算答案。
考虑莫队如何应用暴力求答案。右端点是单调的,所以可以用一个栈维护,并记录每个数字对应可选的位置即可。
时间复杂度: O(nn√)
SRC
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std ;
#define N 500000 + 10
const int inf = 0x7FFFFFFF ;
struct Note {
int v , h ;
} tp[N] ;
struct Query {
int l , r , h ;
} Q[N] ;
bool flag[N] ;
int a[N] , Belong[N] ;
int tmp[N] , S[N] , P[N] , Next[N] ;
int n , m , Block , Cnt ;
int Ans[N] ;
bool cmp1( Note a , Note b ) { return a.v < b.v ; }
bool cmp2( Query a , Query b ) { return Belong[a.l] < Belong[b.l] || ( Belong[a.l] == Belong[b.l] && a.r < b.r ) ; }
void Pre( int l , int r ) {
int top = 0 ;
for (int i = r ; i >= l ; i -- ) {
while ( top && a[i] > a[S[top]] ) top -- ;
if ( top && a[i] != a[S[1]] ) flag[i] = 0 ;
else flag[i] = 1 ;
if ( top && a[i] == a[S[top]] ) P[i] = S[top] ;
else {
P[i] = i ;
S[++top] = i ;
}
}
}
int BF( int l , int r ) {
int top = 0 , ans = 1 ;
for (int i = l ; i <= r ; i ++ ) {
while ( top && a[i] > a[tmp[top]] ) top -- ;
if ( top && a[i] == a[tmp[top]] ) {
ans = max( ans , i - tmp[top] + 1 ) ;
} else {
tmp[++top] = i ;
}
}
return ans ;
}
int main() {
freopen( "sequence.in" , "r" , stdin ) ;
freopen( "sequence.out" , "w" , stdout ) ;
scanf( "%d%d" , &n , &m ) ;
for (int i = 1 ; i <= n ; i ++ ) {
scanf( "%d" , &a[i] ) ;
tp[i].v = a[i] ;
tp[i].h = i ;
}
sort( tp + 1 , tp + n + 1 , cmp1 ) ;
for (int i = 1 ; i <= m ; i ++ ) {
if ( tp[i].v != tp[i-1].v ) ++ Cnt ;
a[tp[i].h] = Cnt ;
}
Block = sqrt(n) ;
for (int i = 1 ; i <= n ; i ++ ) Belong[i] = i / Block + ( i % Block != 0 ) ;
for (int i = 1 ; i <= m ; i ++ ) scanf( "%d%d" , &Q[i].l , &Q[i].r ) , Q[i].h = i ;
sort( Q + 1 , Q + m + 1 , cmp2 ) ;
int ans = 0 , last = 0 ;
for (int i = 1 ; i <= m ; i ++ ) {
if ( Belong[Q[i].l] != Belong[Q[i-1].l] ) {
memset( Next , 0 , sizeof(Next) ) ;
Pre( Block * (Belong[Q[i].l] - 1) + 1 , Block * Belong[Q[i].l] ) ;
S[0] = 0 ;
ans = 1 ;
last = Block * Belong[Q[i].l] + 1 ;
}
if ( Q[i].r < last ) Ans[Q[i].h] = BF( Q[i].l , Q[i].r ) ;
else {
for (int j = last ; j <= Q[i].r ; j ++ ) {
while ( S[0] && a[j] > a[S[S[0]]] ) S[0] -- ;
if ( !S[0] || a[j] == a[S[1]] ) Next[a[j]] = j ;
if ( S[0] && a[j] == a[S[S[0]]] ) {
ans = max( ans , j - S[S[0]] + 1 ) ;
} else S[++S[0]] = j ;
}
int now = 1 ;
for (int j = Block * Belong[Q[i].l] ; j >= Q[i].l ; j -- ) {
if ( flag[j] ) now = max( now , Next[a[j]] - j + 1 ) ;
now = max( now , P[j] - j + 1 ) ;
}
Ans[Q[i].h] = max( now , ans ) ;
}
last = max( last , Q[i].r ) ;
}
for (int i = 1 ; i <= m ; i ++ ) printf( "%d\n" , Ans[i] ) ;
return 0 ;
}
以上.