HACKEREARTH: 2 vs 3 (Segment Tree-DS)


HACKEREARTH: 2 vs 3.


///==================================================///
/// HELLO WORLD !! ///
/// IT'S ME ///
/// BISHAL GAUTAM ///
/// [ bsal.gautam16@gmail.com ] ///
///==================================================///
#include<bits/stdc++.h>
#define X first
#define Y second
#define mpp make_pair
#define nl printf("\n")
#define SZ(x) (int)(x.size())
#define pb(x) push_back(x)
#define pii pair<int,int>
#define pll pair<ll,ll>
///---------------------
#define S(a) scanf("%d",&a)
#define P(a) printf("%d",a)
#define SL(a) scanf("%lld",&a)
#define S2(a,b) scanf("%d%d",&a,&b)
#define SL2(a,b) scanf("%lld%lld",&a,&b)
///------------------------------------
#define all(v) v.begin(),v.end()
#define CLR(a) memset(a,0,sizeof(a))
#define SET(a) memset(a,-1,sizeof(a))
#define fr(i,a,n) for(int i=a;i<=n;i++)
using namespace std;
typedef long long ll;
///==========CONSTANTS=============///
/// Digit 0123456789012345678 ///
#define MX 100005
#define inf 2000000000
#define MD 3
#define eps 1e-9
///===============================///

int nd[(4*MX)+2];
int ar[MX+2],Pw[MX+2];

void Build(int id,int l,int r) {
if(l==r) {
nd[id]=ar[l];
return;
}
int md=(l+r)>>1,lft=(id<<1),rgt=lft+1;
Build(lft,l,md);
Build(rgt,md+1,r);
nd[id]=(nd[rgt]+(Pw[(r-md)]*nd[lft])%MD)%MD;
}

void Upd(int id,int l,int r,int p) {
if(l==r){
nd[id]=1;
return;
}
int md=(l+r)>>1,lft=(id<<1),rgt=lft+1;
if(p<=md)Upd(lft,l,md,p);
else Upd(rgt,md+1,r,p);
nd[id]=(nd[rgt]+(Pw[(r-md)]*nd[lft])%MD)%MD;
}

int Qry(int id,int l,int r,int q1,int q2) {
if( l==q1 && r==q2 ) return nd[id];
int md=(l+r)>>1,lft=(id<<1),rgt=lft+1;
if( q2<=md ) return Qry(lft,l,md,q1,q2);
else if(q1>md ) return Qry(rgt,md+1,r,q1,q2);
else {
int x=Qry(lft,l,md,q1,md);
int y=Qry(rgt,md+1,r,md+1,q2);
return (y+(Pw[ q2-md ]*x)%MD)%MD;
}
return 0;
}

int main() {
int m,n,i,j,k,x,y,op;
Pw[0]=1;
for(i=1; i<=MX; i++) {
Pw[i]=(Pw[i-1]*2)%MD;
}
S(n);
fr(i,1,n)scanf("%1d",&ar[i]);
Build(1,1,n);
//cout<<nd[1]<<endl;
S(m);
while(m--) {
S(op);
if(op==1) {
S(x);
x++;
if( ar[x]==0 ) {
///flip val of x indx iff the val at that indx is 0
Upd(1,1,n,x);
ar[x]=1;
}
} else { /// value of the binary string from x to y
S2(x,y);
x++,y++;
int ans=Qry(1,1,n,x,y);
printf("%d\n",ans%MD);
}
}
return 0;
}

Comments

Popular posts from this blog

HackerEarth: City and Campers 2 (DSU-UnionFind)

Two Pointers Technique & Binary Search For Beginners

Problem : Codeforces Round #406 (Div. 1) B [ Legacy ]( Dijakstra, Segment tree)