-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathBit Inversions.cpp
67 lines (56 loc) · 1.29 KB
/
Bit Inversions.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <bits/stdc++.h>
using namespace std;
const int maxN = 2e5+5;
const int SIZE = 4*maxN;
int N, M, mp[maxN], lo[SIZE], hi[SIZE], dp[3][SIZE];
char S[maxN];
int len(int i){
return hi[i]-lo[i]+1;
}
int combine(int a, int b){
return ((a<0)^(b<0)) ? a : a+b;
}
bool allsame(int i){
return abs(dp[2][i]) == len(i);
}
void pull(int i){
dp[0][i] = (allsame(2*i) ? combine(dp[0][2*i], dp[0][2*i+1]) : dp[0][2*i]);
dp[1][i] = (allsame(2*i+1) ? combine(dp[1][2*i+1], dp[1][2*i]) : dp[1][2*i+1]);
dp[2][i] = max(abs(combine(dp[1][2*i], dp[0][2*i+1])), max(dp[2][2*i], dp[2][2*i+1]));
}
void init(int i, int l, int r){
lo[i] = l; hi[i] = r;
if(l == r){
mp[l] = i;
dp[0][i] = dp[1][i] = (S[l-1] == '0' ? -1 : 1);
dp[2][i] = abs(dp[0][i]);
return;
}
int m = (l+r)/2;
init(2*i, l, m);
init(2*i+1, m+1, r);
pull(i);
}
void update(int idx){
int i = mp[idx];
dp[0][i] *= -1;
dp[1][i] = dp[0][i];
i >>= 1;
while(i){
pull(i);
i >>= 1;
}
}
int query(){
return dp[2][1];
}
int main(){
scanf("%s %d", S, &M);
N = (int) strlen(S);
init(1, 1, N);
for(int i = 0, x; i < M; i++){
scanf("%d", &x);
update(x);
printf("%d%c", query(), (" \n")[i==M-1]);
}
}