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

posted @ 2021-05-15 16:37  RioTian  阅读(522)  评论(0编辑  收藏  举报