My 1st Solution using OOP concept in C++, This solution give me Wrong Answer on Codechef
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
#define LEN 100005
class SegmentTree{
int *Tree;
bool *Lazy;
public :
SegmentTree(){
Tree=new int[4*LEN]();
memset(Tree,0,4*LEN*sizeof(int));
Lazy=new bool[4*LEN]();
memset(Lazy,0,4*LEN*sizeof(bool));
}
void update(int l,int r,int inx,int ql,int qr)
{
if(qr<l || ql>r ||l>r)
return ;
if(Lazy[inx])
{
Tree[inx]=(r-l+1)-Tree[inx];
if(l!=r)
{
Lazy[2*inx+1]=!Lazy[2*inx+1];
Lazy[2*inx+2]=!Lazy[2*inx+2];
}
Lazy[inx]=0;
}
if(ql<=l && r<=qr)
{
Tree[inx]=(r-l+1)-Tree[inx];
if(l!=r)
{
Lazy[2*inx+1]=!Lazy[2*inx+1];
Lazy[2*inx+2]=!Lazy[2*inx+2];
}
return ;
}
update(l,(l+r)/2,2*inx+1,ql,qr);
update((l+r)/2+1,r,2*inx+2,ql,qr);
Tree[inx]=Tree[2*inx+1]+Tree[2*inx+2];
}
int getQuery(int l,int r,int ql,int qr,int inx)
{
if(l>r || qr<l || ql>r)
return 0;
if(Lazy[inx])
{
Tree[inx]=(r-l+1)-Tree[inx];
if(l!=r)
{
Lazy[2*inx+1]=!Lazy[2*inx+1];
Lazy[2*inx+2]=!Lazy[2*inx+2];
}
Lazy[inx]=0;
}
if(ql<=l && r<=qr)return Tree[inx];
return getQuery(l,(l+r)/2,ql,qr,2*inx+1)+getQuery((l+r)/2+1,r,ql,qr,2*inx+2);
}
};
int main()
{
int n,q,l,r,op,i,j;
cin>>n>>q;
SegmentTree objTree;
while(q--)
{
cin>>op>>l>>r;
if(op==0)
objTree.update(0,n-1,0,l,r);
else
cout<<objTree.getQuery(0,n-1,l,r,0)<<endl;
}
return 0;
}
Why this solution is wrong When I submit solution without class and object it accepted by Codechef
2nd Solution without class and object and its accepted by codechef
/*
Flipping Coins
Problem code: FLIPCOIN
*/
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
#define LEN 100005
int Tree[4*LEN]={0};
bool Lazy[4*LEN]={false};
void update(int l,int r,int inx,int ql,int qr)
{
if(Lazy[inx])
{
Tree[inx]=(r-l+1)-Tree[inx];
if(l!=r)
{
Lazy[2*inx+1]=!Lazy[2*inx+1];
Lazy[2*inx+2]=!Lazy[2*inx+2];
}
Lazy[inx]=0;
}
if(qr<l || ql>r ||l>r)
return ;
if(ql<=l && r<=qr)
{
Tree[inx]=(r-l+1)-Tree[inx];
if(l!=r)
{
Lazy[2*inx+1]=!Lazy[2*inx+1];
Lazy[2*inx+2]=!Lazy[2*inx+2];
}
return ;
}
update(l,(l+r)/2,2*inx+1,ql,qr);
update((l+r)/2+1,r,2*inx+2,ql,qr);
Tree[inx]=Tree[2*inx+1]+Tree[2*inx+2];
}
int getQuery(int l,int r,int ql,int qr,int inx)
{
if(l>r || qr<l || ql>r)
return 0;
if(Lazy[inx])
{
Tree[inx]=(r-l+1)-Tree[inx];
if(l!=r)
{
Lazy[2*inx+1]=!Lazy[2*inx+1];
Lazy[2*inx+2]=!Lazy[2*inx+2];
}
Lazy[inx]=0;
}
if(ql<=l && r<=qr)
return Tree[inx];
return getQuery(l,(l+r)/2,ql,qr,2*inx+1)+getQuery((l+r)/2+1,r,ql,qr,2*inx+2);
}
int main()
{
int n,q,l,r,op,i,j;
cin>>n>>q;
while(q--)
{
cin>>op>>l>>r;
if(op==0)
update(0,n-1,0,l,r);
else
cout<<getQuery(0,n-1,l,r,0)<<endl;
}
return 0;
}