New Start onwards: Learning Bitset in C++
Bitset
This is a C++ STL library that can be used as bool and all bitwise operations can be performed on it.
It is declared as bitset<size> name; here size is the number of bits you want. For example, if size=10 it will act as a bool array of size 10.
you can set ith bit by using "name.set(i);" but note the bit indexing starts from the right side and from 0. If our bit set is for example bitset<12>name; and we used name.set(5) the result will be 000000100000.
also, there's an interesting thing
here in the above code, you will see in the val bitset we set 1,5 and 8th (indexes) and in diff bitset we perform an operation for each i which is true, diff|= (val>>i) or (diff =diff||(val>>i)) so we perform 'or'operation of diff using val.
So what happens is let's say we have initial val 0010001000 where bit 3 and bit 7 is 1 or set.
if we perform operation val>>3 we will get 0000001001 we get bit 0 and bit 4 set. We can say that this shift operation caused (j-3) bit to get set (7-3 and 3-3) where j is every set bit on left of 3.So when we perform Val>>i we shift it by i and all the bits (j-i) where j is every set bit on left or eqaul to i.
and this is O(n) operation for following code
for(i=0;i<=10;i++)
{
for(j=i;j<10;j++)
{
diff=val[j]-val[i];
}
}
which is an O(n^2) operation.
we can similarly do for addition. we just have to perform left shift for that.
I am still learning it so I while I discover more operations I will keep adding.
This approach was used in the Codechef ADDSQURE question which came in October Long 2020 where I couldn't do it for full marks. Full marks solution O(n) for it and my O(n^2) solution are below.
Full marks O(n)
My solution O(n^2)
Comments
Post a Comment