Luogu洛谷 P1157 组合的输出

题目

题目链接

Luogu洛谷 P1157 组合的输出

题解

和P1036一样,利用子集枚举,子集的元素数量为r时候,输出。

关键在按照字典序输出。所以从全集枚举到0,从最高位到最低位表示元素1到n,就可以让1尽量出现在靠前的位置。

比如让10110早于10101出现,符合题目的字典序要求。

Then show the code.

#include <cstdio>

int a[30], cnt, n, r;

int main(){
    scanf("%d%d", &n, &r);
    //从全集枚举到0
    for(int s=(1<<n)-1; s>=0; s--){
        cnt = 0;
        for(int i=0; i<n; i++)
            if(s & (1<<i)) a[cnt++] = i;
        //当元素数量与r相同时
        if(cnt == r){
            //因为最高位表示1 所以需要倒着输出
            for(int i=cnt-1; i>=0; i--)
                printf("%3d", n-a[i]);
            printf("\n");
        }
    }
    return 0;
}
posted @ 2021-01-28 17:27  1v7w  阅读(124)  评论(0编辑  收藏  举报