二进制-枚举子集

话说大诗人李白,一生好饮。幸好他从不开车。

一天,他提着酒壶,从家里出来,酒壶中有酒两斗。他边走边唱:

  • 无事街上走,提壶去打酒。
  • 逢店加一倍,遇花喝一斗。

这一路上,他一共遇到店 55 次,遇到花 10

10 次,已知最后一次遇到的是花,他正好把酒喝光了。请你计算李白遇到店和花的次序,有多少种可能的方案。

这个题目解法很多,二进制枚举是一种写起来非常简洁的解法。我们已知遇店 55 次,遇花 1010 次,并且最后一次遇到花,正好把酒喝光。那么我们可以把店作为二进制中的 11,把花作为二进制中的 00,因为已经确定最后一次遇到的是花,所以我们需要判断枚举的结果是否刚好有 55 个 11 和 99 个 00。那么我们就枚举出 1414 位二进制的所有可能并加以判断即可,判断思路为判断二进制是否有 99 个 0055 个 11,并且最终酒刚好剩 11 斗。

附上代码

#include <cstdio>
#include <algorithm>

using namespace std;

int main(){

    int value = 0;
    for(int i = 0;i < (1<<14);i ++){
        int total1 = 0;
        int total2 = 0;
        int num = 2;
        for(int j = 0;j < 14;j ++){
            if(i&(1<<j)){//判断j位是否为1
                total1 ++;
                num *= 2;
            }else{
                total2 ++;
                num -= 1;
            }
        }
        if(total1 == 5&&total2 == 9&&num == 1){
            value ++;
        }
    }
    printf("%d\n",value);
    return 0;
}

本文章来自计蒜客。

猜你喜欢

转载自blog.csdn.net/pack__pack/article/details/55805179