Time Limit: 2 second(s) | Memory Limit: 64 MB |
Given a binary number, we are about to do some operations on the number. Two types of operations can be here.
'I i j' which means invert the bit from i to j (inclusive)
'Q i' answer whether the ith bit is 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 integer having length n (1 ≤ n ≤ 105). The next line will contain an integer q (1 ≤ q ≤ 50000) denoting the number 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 query will be in the form 'Q i' where i is an integer and1 ≤ i ≤ n.
Output
For each case, print the case number in a single line. Then for each query 'Q i' you have to print 1 or 0 depending on the ith bit.
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 |
Note
Dataset is huge, use faster i/o methods.
题意:
有一字符串只包含0和1,然后又m组操作,I L R是将从L到R的字符进行翻转操作0变为1、1变为0,Q x表示询问第x的字符。
思路:
我们只需要计算对询问的字符进行了多少次翻转,如果是偶数次,该字符变,否则翻转。对于区间的更新,我们可以使用线段树,不过对于这个题,因为只是对点的查询,而且每个节点的初始值都相同,为0,因此我们可以直接使用树状数组。下面是一个很巧妙的做法,而且很容易理解。
用了树状数组的区间更新 单点查找(一般为单点更新 区间查找)
例如 区间(2,4)加1
则Updata(2,1) Updata(4+1,-1)
实现了更新(2,4)的值而不改变其他值
求Sum时即可得到某一点的值
AC代码:
#include <stdio.h>
#include <string.h>
#include<algorithm>
using namespace std;
char s[100010];
int n;
int sum[100010];
int lowbit(int x)
{
return x&(-x);
}
void change(int x, int v)
{
while (x <= n)
{
sum[x] += v;
x += lowbit(x);
}
}
int get(int x)
{
int s = 0;
while (x)
{
s += sum[x];
x -= lowbit(x);
}
return s;
}
void update(int l, int r)
{
change(l, 1);
change(r+1, -1);
}
int main()
{
int t,m,k=1;
scanf("%d",&t);
while(t--)
{
memset(sum, 0, sizeof(sum));
scanf("%s",s);
scanf("%d",&m);
n =strlen(s);
char op;
int l, r;
printf("Case %d:\n",k++);
while (m--)
{
getchar();
scanf("%c",&op);
if (op == 'I')
{
scanf("%d %d",&l, &r);
update(l, r);
}
else
{
scanf("%d",&l);
if (get(l)%2 == 1)
{
if (s[l-1] == '1')
puts("0");
else
puts("1");
}
else
printf("%c\n",s[l-1]);
}
}
}
return 0;
}