Sunteți pe pagina 1din 4

4/14/2016

BITMASKSFORBEGINNERSCodeforces

Enter|Register
HOME

SURAJ021

CONTESTS
BLOG

TEAMS

GYM

PROBLEMSET

SUBMISSIONS

GROUPS

RATING

API

VK CUP

CROC

CONTESTS

Payattention

suraj021'sblog

BITMASKSFORBEGINNERS
Bysuraj021,11monthsago,

IwashavingtroubleunderstandingBitmask,thenIfoundanunknownpdfaboutBitmaskon
google.IwouldliketohelpthebeginnerslikemeinunderstandingBitmasksandtheiruses.
Herewego:
####MOTIVATION

Beforecontest

CROC2016FinalRound[Private,
ForOnsiteFinalistsOnly]
27:41:12
Like 55peoplelikethis.SignUptoseewhat
yourfriendslike.

Toprated

User

Rating

Supposeyouhaveasetofobjectsandyouwantsomewaytorepresentwhichobjectsto
pickandwhichonesnotto
pick.Howdoyourepresentthatininaprogram?Moregenerally,howdoyourepresenta
subestofaset?OnewayistouseaMaptoassociatewitheachobjectabooleanvalue
indicatingwhethertheobjectispicked.Alternatively,iftheobjectcanbeindexedbyintegers,
youcanuseabooleanarray.However,thistakesupalotofmemoryandcanbeslowdue
totheoverheadofMapandarray.Ifthesizeofthesetisnottoolarge,abitmaskismuch
moreefficient(andconvenient)!

tourist

3588

TooDifficuIt

3378

Petr

3342

rng_58

3102

izrak

3073

jcvb

3036

Um_nik

2994

####WHATISBITMASKS?

vepifanov

2985

Egor

2978

10

RomaWhite

Bitmasksa.k.a.lightweight,smallsetsofBooleans(nativesupportinC/C++/Java).An
integerisstoredinacomputersmemoryasasequence/stringofbits.Thus,wecanuse
integerstorepresentalightweightsmallsetofBooleanvalues.Allsetoperationsthen
involveonlythebitwisemanipulationofthecorrespondinginteger,whichmakesitamuch
moreefficientchoicewhencomparedwiththeC++STLvector,bitset,orsetoptions.Such
speedisimportantincompetitiveprogramming.
Weknowanintegerisjustabunchofbitsstringedtogether.The1stbitwillrepresent
whetherthe1stobjectispicked,the2ndbitwillrepresentwhetherthe2ndobjectispicked
ornot,etc.Forexample,supposeinasetof5objects,wehavepickedthe1st,3rd,and
4thobject.Thebitmasktorepresentthisinbinaryis01101or13indecimal(inthenotes,
the1stbitwillalwaysbetheleastsignificantbitandwillalwaysappearattheveryright).
####MANIPULATINGBITMASKS
1.REPRESENTATION:A32(or64)bitsignedintegerforupto32(or64)
items.(Toavoidissueswiththe
twoscomplementrepresentation,usea32bit/64bitsignedintegerto
representbitmasksofupto
30/62itemsonly,respectively).
Forexample:5|4|3|2|1|0<0
basedindexingfromright
32|16|8|4|2|1<power
of2
A=34(base10)=1|0|0|0|1|0<in
binary
F|E|D|C|B|A<
alternativealphabetlabel
Intheexampleabove,theintegerA=34or100010inbinaryalso
representsasmallset{1,5}witha
0basedindexingschemeinincreasingdigitsignificance(or{B,F}
usingthealternativealphabet
label)becausethesecondandthesixthbits(countingfromtheright)
ofAareon(1).
http://codeforces.com/blog/entry/18169

Countries |Cities |Organizations

2976
Viewall

Topcontributors

User

Contrib.

Errichto

167

Petr

165

Zlobober

163

Edvard

158

Xellos

154

chrome

147

Swistakk

145

rng_58

142

amd

140

Rubanenko

140
Viewall

Finduser

Handle:
Find

Recentactions

Akylbek_AitkaliCROC2016
raj454rajStopStalk:Tooltomaintainyour
algorithmicprogress
chromeTopcoderOpenAlgorithmRound
1B2016

1/4

4/14/2016

BITMASKSFORBEGINNERSCodeforces
bipinb1994B.TechHonor'sPrograme

2.Tomultiply/divideanintegerby2:
Weonlyneedtoshiftthebitsinthe
integerleft/right,respectively.
Noticethatthetruncationintheshiftrightoperationautomatically
roundsthedivisionby2down,
e.g.17/2=8.
Forexample:A=34(base10)=100010(base
2)
A=A<<1=A*2=68(base10)=1000100(base
2)
A=A>>2=A/4=17(base10)=10001(base2)
A=A>>1=A/2=8(base10)=1000(base2)
<LSB(LeastSignificantBit)isgone

ReynaSRM688andCROC2016Final
roundcoincide
anuraganandInvitationforBitwise2016
ni3_ksBeginningWithCompetitive
Programming
smallid01helpmewithaneasygym
problem
zscoderCodechefAprilChallenge2016
BriefSolutions
aduryskInsomnia2016
yusupjammadovGoogleCodeJam2016

lewinCodeforcesRound#309Editorial
tweetyListofIOI2016Participants

3.Addthejthobjecttothesubset(setthejthbitfrom0to1):
usethebitwiseORoperationA|=(1<<j).
Forexample:A=34(base10)=100010(base2)
j=3,1<<j=001000<bit1isshiftedto
theleft3times
OR(trueifeitherofthe
bitsistrue)
A=42(base10)=101010(base2)//updateAto
thisnewvalue42
4.Removethejthobjectfromthesubset(setthejthbitfrom1to0):
usethebitwiseANDoperationA&=(1<<j).
Forexample:A=42(base10)=101010(base2)
j=1,~(1<<j)=111101<~isthebitwise
NOToperation
AND
A=40(base10)=101000(base2)//updateAto
thisnewvalue40
5.Checkwhetherthejthobjectisinthesubset(checkwhetherjthbitis
1):
usethebitwiseANDoperationT=A&(1<<j).
IfT=0,thenthejthitemofthesetisoff.

NickolasVKCup2016WildCardRound1:
editorial
AzorAhaiProblemsonpalindromicTree,
treapsanddpoptimizationusingconvex
hull?
sumit93BitmaskDP
_indexStrangecompilationerror
temp_testCompetitiveprogramming
EdvardEducational
CodeforcesRound9
mahim007gettingtimelimitexceededon
SPOJ"MCOINSCoinsGame"problem.pls
someonehelpme.
LeonidDeadline24Finalists[2016]
ACRageOMG!
utkarshlZenhacksprogrammingcontest

YamiNoKirinQuestionAboutTarjan's
AlgorithmforStronglyConnected
Components
stouldWorkingon1dcoordinate.
Detailed

IfT!=0(tobeprecise,T=(1<<j)),thenthejthitemoftheset
ison.
Forexample:A=42(base10)=101010(base2)
j=3,1<<j=001000<bit1isshiftedtothe
left3times
AND(onlytrueifbothbits
aretrue)
T=8(base10)=001000(base2)>notzero,the3rd
itemison
6.Totoggle(flipthestatusof)thejthitemoftheset:
usethebitwiseXORoperationA=(1<<j).
Forexample:A=40(base10)=101000(base2)
j=2,(1<<j)=000100<bit1isshiftedto
theleft2times
XOR<trueifbothbits
aredifferent
A=44(base10)=101100(base2)//updateAto
thisnewvalue44
7.Togetthevalueoftheleastsignificantbitthatison(firstfromthe
http://codeforces.com/blog/entry/18169

2/4

4/14/2016

BITMASKSFORBEGINNERSCodeforces

right):
useT=(A&(A)).
Forexample:A=40(base10)=000...000101000(32bits,base2)
A=40(base10)=111...111011000(twoscomplement)
AND
T=8(base10)=000...000001000(3rdbitfromright
ison)
8.Toturnonallbitsinasetofsizen:(becarefulwithoverflows)
useA=(1<<n)1;
9.Iteratethroughallsubsetsofasetofsizen:
for(x=0;x<(1<<n);++x)
10.Iteratethroughallsubsetsofasubsety(notincludingemptyset):
for(x=y;x>0;x=(y&(x1)))
Exampleofasubsetproblem:givenasetofnumbers,wewanttofindthesumofall
subsets.
Sol:Thisiseasytocodeusingbitmasks.wecanuseanarraytostorealltheresults.
intsum_of_all_subset(vector<int>s){
intn=s.size();
intresults[(1<<n)];//(1<<n)=2^n
//initializeresultsto0
memset(results,0,sizeof(results));
//iteratethroughallsubsets
for(inti=0;i<(1<<n);++i){//foreach
subset,O(2^n)
for(intj=0;j<n;++j){//check
membership,O(n)
if((i&(1<<j))!=0)//testifbitj
isturnedoninsubseti?
results[i]+=s[j];//ifyes,process
j
}
}
}
11.LIMITATIONS:
a.Alwayscheckthesizeofthesettodeterminewhethertouseanint
orlonglongornotusingbitmaskatall
b.Alwaysuseparenthesistoindicatetheprecedenceofoperations
whendoingbitwiseoperations!
Whenitinvolvesbitwiseoperatorsandnotputtingparenthesiscan
yieldundesirableresults!
Forexample,letx=5.Thenx1<<2=16,butx(1<<2)=1
P.S1.Iapologizeforbadformatting.2.Ifyoufindsomethingwrong/inappropriateplease
correctme.3.Examplesarecopiedfromsometextbook4.Cananyonepleasewriteablog
onBacktracking,idon'tgetflowofcontrolinrecursivecallsinbacktrackingwhenacertain
constraintfailsonaconfiguration(likeinNqueensproblem),howdoesprogram
backtracksandhowcontrolflowtakesplacethenandwhathappensafterthat?
ThankYou
bitmask, bitmanipulation, beginners

http://codeforces.com/blog/entry/18169

suraj021

11monthsago

3/4

4/14/2016

BITMASKSFORBEGINNERSCodeforces

Comments(8)

Writecomment?

11monthsago, # |

Cantherebeanythingbetterthanexponentialinsubsetsum?
antivenom

Reply
11monthsago, # |

SEEthislink>beneficialtoall
antivenom

Reply
11monthsago, # |

Copy&pastefromCompetitiveprogrammingbook:D

Reply
SmartCoder
11monthsago, # ^ |

IhavealreadywrittenthatinP.S:D
suraj021

Reply
7weeksago, # ^ |

Andwhichbookmightthatbe?

Reply
VioletNash
9daysago, # ^ |

Justgoogle"CompetitiveProgramming3".BestofLuck
suraj021

Reply

Codeforces(c)Copyright20102016MikeMirzayanov
TheonlyprogrammingcontestsWeb2.0platform
Servertime:Apr/14/201616:00:43UTC+5.5(c3).
Desktopversion,switchtomobileversion.

http://codeforces.com/blog/entry/18169

4/4

S-ar putea să vă placă și