HDU 1716:排列2 ← next_permutation()

【题目来源】
http://acm.hdu.edu.cn/showproblem.php?pid=1716

【题目描述】
Ray又对数字的列产生了兴趣:
现有四张卡片,用这四张卡片能排列出很多不同的4位数,要求按从小到大的顺序输出这些4位数。

【输入格式】
每组数据占一行,代表四张卡片上的数字(0<=数字<=9),如果四张卡片都是0,则输入结束。

【输出格式】
对每组卡片按从小到大的顺序输出所有能由这四张卡片组成的4位数,千位数字相同的在同一行,同一行中每个四位数间用空格分隔。
每组输出数据间空一行,最后一组数据后面没有空行。

【输入样例】
1 2 3 4
1 1 2 3
0 1 2 3
0 0 0 0

【输出样例】
1234 1243 1324 1342 1423 1432
2134 2143 2314 2341 2413 2431
3124 3142 3214 3241 3412 3421
4123 4132 4213 4231 4312 4321

1123 1132 1213 1231 1312 1321
2113 2131 2311
3112 3121 3211

1023 1032 1203 1230 1302 1320
2013 2031 2103 2130 2301 2310
3012 3021 3102 3120 3201 3210

【算法代码】

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

int main() {
    int a[4];
    while(1) {
        scanf("%d%d%d%d",&a[0],&a[1],&a[2],&a[3]);
        if(a[0]+a[1]+a[2]+a[3]==0) break;
        sort(a,a+4);
        int flag=0;
        int t;

        do {
            if(a[0]==0) continue;
            else if(flag==0) {
                printf("%d%d%d%d",a[0],a[1],a[2],a[3]);
                flag=1;
            } else if(t==a[0]) {
                printf(" %d%d%d%d",a[0],a[1],a[2],a[3]);
            } else {
                printf("\n%d%d%d%d",a[0],a[1],a[2],a[3]);
            }
            t=a[0];
        } while(next_permutation(a,a+4));

        printf("\n\n");
    }
    return 0;
}


/*
in:
1 2 3 4
1 1 2 3
0 1 2 3
0 0 0 0

out:
1234 1243 1324 1342 1423 1432
2134 2143 2314 2341 2413 2431
3124 3142 3214 3241 3412 3421
4123 4132 4213 4231 4312 4321

1123 1132 1213 1231 1312 1321
2113 2131 2311
3112 3121 3211

1023 1032 1203 1230 1302 1320
2013 2031 2103 2130 2301 2310
3012 3021 3102 3120 3201 3210
*/

【参考文献】
https://blog.csdn.net/qie_wei/article/details/81068186
https://blog.csdn.net/qq_31741481/article/details/84530287
https://cplusplus.com/reference/algorithm/next_permutation/

相关推荐
阿巴~阿巴~3 天前
深入解析C++ STL链表(List)模拟实现
开发语言·c++·链表·stl·list
郝学胜-神的一滴3 天前
基于C++的词法分析器:使用正则表达式的实现
开发语言·c++·程序人生·正则表达式·stl
一匹电信狗3 天前
【C++】异常详解(万字解读)
服务器·c++·算法·leetcode·小程序·stl·visual studio
Hard but lovely4 天前
C++:stl-> list的模拟实现
开发语言·c++·stl·list
_poplar_10 天前
09 【C++ 初阶】C/C++内存管理
c语言·开发语言·数据结构·c++·git·算法·stl
半桔13 天前
【STL源码剖析】从源码看 vector:底层扩容逻辑与内存复用机制
java·开发语言·c++·容器·stl
乌萨奇也要立志学C++13 天前
【C++详解】STL-set和map的介绍和使用样例、pair类型介绍、序列式容器和关联式容器
开发语言·c++·stl
序属秋秋秋14 天前
《C++初阶之STL》【模板参数 + 模板特化 + 分离编译】
开发语言·c++·笔记·学习·stl
Layflok19 天前
《黑马笔记》 --- C++ 提高编程
开发语言·c++·stl
一匹电信狗22 天前
【C++】手搓一个STL风格的vector容器
c语言·数据结构·c++·算法·leetcode·stl·visual studio