Binary Simulation
Time Limit: 2 second(s) | Memory Limit: 64 MB |
Given a binary number, we are about to do some operations onthe number. Two types of operations can be here.
'I i j' which means invert the bit from itoj (inclusive)
'Q i' answer whether the ith bitis 0 or 1
The MSB (most significant bit) is the first bit (i.e. i=1).The binary number can contain leading zeroes.
Input
Input starts with an integer T (≤ 10),denoting the number of test cases.
Each case starts with a line containing a binary integerhaving length n (1 ≤ n ≤ 105). The nextline will contain an integer q (1 ≤ q ≤ 50000) denoting thenumber of queries. Each query will be either in the form'I i j' where i,j are integers and 1 ≤ i ≤ j ≤ n. Or the querywill be in the form'Q i' where i is an integer and 1 ≤i ≤ n.
Output
For each case, print the case number in a single line. Thenfor each query 'Q i' you have to print 1 or 0 depending on the ithbit.
Sample Input | Output for Sample Input |
2 0011001100 6 I 1 10 I 2 7 Q 2 Q 1 Q 7 Q 5 1011110111 6 I 1 10 I 2 7 Q 2 Q 1 Q 7 Q 5 | Case 1: 0 1 1 0 Case 2: 0 0 0 1 |
区间更新,本来想用数组作标记来做,发现做不了,看过题解才知道有专门解决区间更新的算法--树状数组,线段树
给出任意多个区间i,j,i到j之间的数字翻转,最后问第n个数字是什么,只有0和1即计算这个数字翻转了几次
奇数次就是翻转后的数,偶数次就是本身不变。
这题树状数组简单一些
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<map>
#include<queue>
#include<algorithm>
#include<cmath>
#include<vector>
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define DL(a, b) memset(a, b, sizeof(a))
using namespace std;
typedef long long LL;
const int maxn = 1e5+10;
int put[maxn];
char str[maxn];
int lowbit(int x){
return x&(-x);
}
void change(int s, int val, int n){
while(s <= n){
put[s] += val;
s += lowbit(s);
}
}
int get_bit(int s){
int t = 0;
while(s){
t += put[s];
s -= lowbit(s);
}
return t;
}
int main(){
int t, n, m, c, kcase = 1;
char ch;
scanf("%d", &t);
while(t--){
DL(put, 0);
scanf("%s", str+1);
scanf("%d", &n);
m = strlen(str+1);
printf("Case %d:\n", kcase++);
for(int i = 0; i < n; i++){
scanf(" %c", &ch);
if(ch == 'I'){
int st, en;
scanf("%d %d", &st, &en);
change(st, 1, m);//区间起点+1,终点后一位-1,根据树状数组的特性,就相当于st到en区间都+1
change(en+1, -1, m);
continue;
}
scanf("%d", &c);
printf("%d\n", get_bit(c)&1 ? !(str[c]-48) : str[c]-48);//最后单点查询该点翻转过几次
}
}
return 0;
}