Harolinch's blog

By Harolinch, history, 3 months ago, In English,

i'm trying to solve a dp problem involves bitmasks and when i see others code, all of them have the these lines

for(mask = 0; mask < (1 << k); mask++){
    ..
    for(submask = (mask - 1) & mask; submask > 0; submask = (submask - 1) & mask){
        ..
    }

what these lines means ?

 
 
 
 
  • Vote: I like it  
  • +1
  • Vote: I do not like it  

»
3 months ago, # |
Rev. 4   Vote: I like it 0 Vote: I do not like it

It iterates all over subsets consist of only bit 1 of mask.

For example if mask = 6 (110 in binary representation), then it iterates over 6 (110), 4(100), 2(010).

Edit: Sorry, I thought it was submask = mask. Because it initialize submask = (mask-1) & mask so it will iterates over 4 and 2 only.

  • »
    »
    3 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    i didn't get it yet, what is the relation between submask and mask ? i know it's "subset" of mask but how they relate to others

»
3 months ago, # |
  Vote: I like it +1 Vote: I do not like it

First loop iterate masks in range 0 to 2^k — 1. Second loop iterate all submasks of current mask. This code works on O(3^k). Read this.

  • »
    »
    3 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thanks so much, that is reaaly the answer i was looking for