Harolinch's blog

By Harolinch, history, 6 years 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

| Write comment?
»
6 years 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.

»
6 years 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.