C++中全排列函数next_permutation(2)

P1157 组合的输出 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

全排列的新用法:

排列与组合是常用的数学方法,其中组合就是从nn个元素中抽出r个元素(不分顺序且r \le n)rn),我们可以简单地将nn个元素理解为自然数1,2,…,n1,2,,n,从中任取rr个数。

现要求你输出所有组合。

例如n=5,r=3n=5,r=3,所有组合为:

12 3 , 1 2 4 , 1 2 5 , 1 3 4 ,1 3 5 , 1 4 5 , 2 3 4 , 2 3 5 , 2 4 5 , 3 4 5

#include<cstdio>
#include<algorithm>
int x[30];//x[i]代表第i选或不选,0代表选,1代表不选
using namespace std;
int main(){
    int n,r;
    scanf("%d%d",&n,&r);//读入n、r
    for(int i=r+1;i<=n;++i)
        x[i]=1; //赋初始值
    do{
        for(int i=1;i<=n;++i)
            if(x[i]==0) printf("%3d",i);//如果是0就输出,注意三个常宽
        printf("\n");//换行
    }while(next_permutation(x+1,x+n+1));//生成下一个
    return 0;//返回
}

该题解转自题解 P1157 【组合的输出】 - tony123456 的博客 - 洛谷博客 (luogu.com.cn),具体的思路是把前后面的数字赋值为1,为0的数字有r个,对于整个数组进行全排列,为0的进行输出。保证了数字的个数

posted @ 2022-03-09 16:01  i天天开心  阅读(20)  评论(1编辑  收藏  举报