HDU 3911 Black And White 线段树
Black And White
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3328 Accepted Submission(s): 1020
4 1 0 1 0 5 0 1 4 1 2 3 0 1 4 1 3 3 0 4 4
1 2 0
传送门:HDU 3911 Black And White
题目大意:给你长度为n的一串01序列,m次操作。n,m<=10^5。
操作有两种:
0 L R 查询区间【L,R】内最长的连续1的长度。
1 L R 翻转区间【L,R】内的数(0变1,1变0)。
题目分析:
区间合并水题。
维护每一个区间的最长前缀。最长后缀,最长子序列即可了。
代码例如以下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std ;
#define rt l , r , o
#define ls ( o << 1 )
#define rs ( o << 1 | 1 )
#define lson l , m , ls
#define rson m + 1 , r , rs
const int maxN = 500000 ;
int lmax[2][maxN] , mmax[2][maxN] , rmax[2][maxN] ;
int cha[maxN] ;
int L , R ;
int max ( const int X , const int Y ) {
return X > Y ? X : Y ;
}
int min ( const int X , const int Y ) {
return X < Y ? X : Y ;
}
void swap ( int &X , int &Y ) {
int tmp ;
tmp = X ;
X = Y ;
Y = tmp ;
}
void Init_PushUp ( int x , int l , int r , int o ) {
int m = ( l + r ) >> 1 ;
lmax[x][o] = lmax[x][ls] ;
if ( lmax[x][ls] == m - l + 1 ) lmax[x][o] += lmax[x][rs] ;
rmax[x][o] = rmax[x][rs] ;
if ( rmax[x][rs] == r - m ) rmax[x][o] += rmax[x][ls] ;
mmax[x][o] = max ( mmax[x][ls] , mmax[x][rs] ) ;
mmax[x][o] = max ( mmax[x][o] , rmax[x][ls] + lmax[x][rs] ) ;
}
void PushUp ( int l , int r , int o ) {
Init_PushUp ( 0 , rt ) ;
Init_PushUp ( 1 , rt ) ;
}
void change ( int o ) {
cha[o] ^= 1 ;
swap ( lmax[0][o] , lmax[1][o] ) ;
swap ( mmax[0][o] , mmax[1][o] ) ;
swap ( rmax[0][o] , rmax[1][o] ) ;
}
void PushDown ( int o ) {
if ( cha[o] ) {
change ( ls ) ;
change ( rs ) ;
cha[o] = 0 ;
}
}
void Build ( int l , int r , int o ) {
cha[o] = 0 ;
if ( l == r ) {
int x ;
scanf ( "%d" , &x ) ;
lmax[x][o] = mmax[x][o] = rmax[x][o] = 1 ;
lmax[x ^ 1][o] = mmax[x ^ 1][o] = rmax[x ^ 1][o] = 0 ;
return ;
}
int m = ( l + r ) >> 1 ;
Build ( lson ) ;
Build ( rson ) ;
PushUp ( rt ) ;
}
void Update ( int l , int r , int o ) {
if ( L <= l && r <= R ) {
change ( o ) ;
return ;
}
PushDown ( o ) ;
int m = ( l + r ) >> 1 ;
if ( L <= m ) Update ( lson ) ;
if ( m < R ) Update ( rson ) ;
PushUp ( rt ) ;
}
int Query ( int l , int r , int o ) {
if ( L <= l && r <= R ) return mmax[1][o] ;
PushDown ( o ) ;
int m = ( l + r ) >> 1 ;
int tmp1 = 0 , tmp2 = 0 , tmp3 = 0 ;
if ( L <= m ) tmp1 = Query ( lson ) ;
if ( m < R ) tmp2 = Query ( rson ) ;
tmp3 = min ( m - L + 1 , rmax[1][ls] ) + min ( R - m , lmax[1][rs] ) ;
return max ( max ( tmp1 , tmp2 ) , tmp3 ) ;
}
void work () {
int n , m , ch ;
while ( ~scanf ( "%d" , &n ) ) {
Build ( 1 , n , 1 ) ;
scanf ( "%d" , &m ) ;
while ( m -- ) {
scanf ( "%d%d%d" , &ch , &L , &R ) ;
if ( 0 == ch ) printf ( "%d\n" , Query ( 1 , n , 1 ) ) ;
if ( 1 == ch ) Update ( 1 , n , 1 ) ;
}
}
}
int main () {
work () ;
return 0 ;
}

浙公网安备 33010602011771号