Advertisement
Riz1Ahmed

BIT/Frenwick Tree Algorithm (LOJ 1080 - Binary Simulation)

Jan 27th, 2020
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. /**BIT/Frenwick Tree Algorithm (LOJ 1080 - Binary Simulation)**\
  2. Given a binary string S & Q query.
  3. Every Query 2 type:
  4. I i j: Invert the bit in range[i:j]
  5. Q i: Print the Bit of S[i] 0 or 1.
  6. Note: 1-Based Indexed.  **/
  7. #include<bits/stdc++.h>
  8. using namespace std;
  9. int tree[100009];
  10. void update(int idx,int v,int n){
  11.     while(idx<=n)
  12.         tree[idx]+=v,
  13.         idx+=(idx& -idx);
  14. }
  15. int query(int idx){
  16.     int sum=0;
  17.     while(idx>0)
  18.         sum+=tree[idx],
  19.         idx-= (idx& -idx);
  20.     return sum;
  21. }
  22. int main(){
  23.     char s[100005],tp[2];
  24.     int n,q,p,i,j,cs=1;
  25.     scanf("%*d");
  26.     while(~scanf("%s",s)){
  27.         int n=strlen(s), ar[n+5];
  28.         memset(tree,0,sizeof (int)*(n+5));
  29.         for (i=0; i<n; i++) ar[i+1]=s[i]-'0';
  30.         scanf("%d",&q);
  31.         printf("Case %d:\n",cs++);
  32.         while(q--){
  33.             scanf("%s %d",tp,&i);
  34.             if (tp[0]=='I'){
  35.                 scanf("%d",&j);
  36.                 update(i,1,n), update(j+1,-1,n);
  37.             }else printf("%d\n",ar[i]^(query(i)&1));
  38.         }
  39.     }
  40.     return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement