Gosper's Hack (生成 n元集合所有 k 元子集

Gosper’s Hack是一种生成 n元集合所有 k元子集的算法,它巧妙地利用了位运算

void GospersHack(int k, int n) {
    int cur = (1 << k) - 1;
    int limit = (1 << n);
    while (cur < limit) {
        // do something
        int lb = cur & -cur;
        int r = cur + lb;
        cur = ((r ^ cur) >> __builtin_ctz(lb) + 2) | r;
        // 或:cur = (((r ^ cur) >> 2) / lb) | r;
    }
}

转自:https://zhuanlan.zhihu.com/p/360512296
例题:https://www.luogu.com.cn/problem/P1441

The desire of his soul is the prophecy of his fate
你灵魂的欲望,是你命运的先知。

原文地址:https://www.cnblogs.com/RioTian/p/14771890.html