全排列next_permutation()的用法

介绍std::next_permutation函数用法,通过示例展示如何利用此函数解决全排列问题,具体应用到蓝桥杯2015年一题中,找到符合特定条件的数字组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.std::next_permutation函数原型

template <class BidirectionalIterator>

  bool next_permutation (BidirectionalIterator first, BidirectionalIterator last );



  template <class BidirectionalIterator, class Compare>

  bool next_permutation (BidirectionalIterator first,BidirectionalIterator last, Compare comp);

说明:next_permutation,重新排列范围内的元素[第一,最后一个)返回按照字典序排列的下一个值较大的组合。

返回值:如果有一个更高的排列,它重新排列元素,并返回true;如果这是不可能的(因为它已经在最大可能的排列),它按升序排列重新元素,并返回false。

简单用法

 #include <cstdio>
 #include <algorithm>
 #include <iostream> 
using namespace std;
int main()
{int a[5];
    for (int i = 0; i < 5; i++) 
            a[i] = i;
     do
     {
     for (int i = 0; i < 5; i++) 
         cout<<a[i];cout<<endl;
     } while (next_permutation(a, a+5));

}

从后向前输出全排列01234——43210
实例
蓝桥2015第3题:竖式加法
题目大意
  祥 瑞 生 辉
  三 羊 献 瑞
−−−−−−−−
 三 羊 生 瑞 气
 
  题目用了8个不同的汉字,表示0~9里八种不同的数字。组成两个数值相加,等于第三个数值。

题解
  定义一个数组int a[10],初始化用a[i]存储i。将a[2]~a[9]与各个汉字对应,然后用next_permutation全排列暴力解,注意三个数值开头不能为0,能解出第2个数值,即“三羊献瑞”对应的数字是1085。
  

/*题解
  定义一个数组int a[10],初始化用a[i]存储i。将a[2]~a[9]与各个汉字对应,然后用next_permutation全排列暴力解,注意三个数值开头不能为0,能解出第2个数值,即“三羊献瑞”对应的数字是1085*/ 
 #include <cstdio>
 #include <algorithm>
using namespace std;

int main() {
    int a[10];
    for (int i = 0; i < 10; i++) a[i] = i;

    do {
        if (!a[2] || !a[6]) continue;
        int x =              a[2]*1000 + a[3]*100 + a[4]*10 + a[5];
        int y =              a[6]*1000 + a[7]*100 + a[8]*10 + a[3];
        int z = a[6]*10000 + a[7]*1000 + a[4]*100 + a[3]*10 + a[9];
        if (x + y == z) printf("%d + %d = %d\n", x, y, z);
    } while (next_permutation(a, a+10));

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YULIU_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值