The document discusses bitwise operations like AND, OR, XOR and bitwise shifts. It explains how bitwise operations work on the bit level of the operands. It also discusses using bitwise operations to represent and manipulate sets as well as solving algorithm problems like finding a singleton element in an array, computing XOR ranges and subset sum using bitwise operations.
6. •
• To clear the i bit in A use A=A&(~(1<<i))
• To check the i bit in A use (A&(1<<i))!=0
To set the ith bit in A use A = A|(1<<i)
th
th
Tuesday, July 3, 12
7. • k mod 2 = k & 1
n = k & (2n - 1)
• k mod 2
Tuesday, July 3, 12
8. Representation of sets
• S = {6,5,4,3,2,1,0}
• B = {2,1,0} can be represented as 0000111
• A = {5,2} can be represented as 0100100
• A U B = 0000111 | 0100100 = 0100111
• A ∩ B = 0000111 & 0100100 = 0000100
• A - B = A & (~B) = 0000111 & 1011011 =
0000011
Tuesday, July 3, 12
9. • What if we want to iterate over all possible
subsets of set S ? Just iterate over all binary
numbers that have |S| bits i.e iterate over
|S| excluding
all binary numbers from 0 to 2
|S|
2
Tuesday, July 3, 12
10. S = A[n]
for(int i = 0;i<1<<n;i++)
//use the ith subset
for(int j = 0;j<n;j++)
if(((1<<j)&i)!=0)
//use the jth element which
//exists in the ith subset
Tuesday, July 3, 12
11. Subset sum
• Given an array of integers of length n, can
you choose some of them (at least one)
such that their sum is zero?
• Constrains n<=20
Tuesday, July 3, 12
12. • assume the array is a set and iterate over
all subsets check if there’s a subset that
sums to zero
Tuesday, July 3, 12
13. Singleton
• Given an array of integers where each
number occurs twice except one find this
number
• Constrains:array size 100000
Tuesday, July 3, 12
17. Pigeonhole principle
• If n items put into m pigeonholes with n>m
then at least one pigeonhole contains more
than one item.
Tuesday, July 3, 12
18. Gray-code like
• Given an array of integers length n where
the hamming distance between any two
consecutive numbers is exactly 1 print Yes if
the array contains four numbers such that
A[i]^A[j]^A[k]^A[l]=0 and 0≤i<j<k<l<n
•
Tuesday, July 3, 12
0≤A[i]<264,n<=100,000
19. • for small n complete search
• for large n solution answer is always YES
Tuesday, July 3, 12
20. X3
• Given an array of integers length n
compute the sum of A[i]^A[j] for all i,j
where i<j
• Constrains n≤1,000,000
Tuesday, July 3, 12
21. • Think of a solution for a simpler problem
then use this solution for the bigger
problem.
• Simpler problem?what if the array
contained only zeroes and ones the answer
would be nZeroes * nOnes where nZeroes
is the count of zeroes and nOnes is count
of ones.
Tuesday, July 3, 12
22. • Similarly we can apply the same approach
th bit
i
for each bit position so the result for
is nZeroes*nOnes*1<<i where nZeroes
and nOnes are the number of zeroes and
ones in the ith bit.
Tuesday, July 3, 12