排列2
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6873 Accepted Submission(s): 2654
Problem Description
Ray又对数字的列产生了兴趣:
现有四张卡片,用这四张卡片能排列出很多不同的4位数,要求按从小到大的顺序输出这些4位数。
现有四张卡片,用这四张卡片能排列出很多不同的4位数,要求按从小到大的顺序输出这些4位数。
Input
每组数据占一行,代表四张卡片上的数字(0<=数字<=9),如果四张卡片都是0,则输入结束。
Output
对每组卡片按从小到大的顺序输出所有能由这四张卡片组成的4位数,千位数字相同的在同一行,同一行中每个四位数间用空格分隔。
每组输出数据间空一行,最后一组数据后面没有空行。
每组输出数据间空一行,最后一组数据后面没有空行。
Sample Input
1 2 3 4 1 1 2 3 0 1 2 3 0 0 0 0
Sample Output
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
Source
Recommend
分析:
这是一道关于排列的问题,常规方法是利用递归求解,但是由于STL中有现成的函数next_permutation(),可以直接调用此函数生成当前排列的下一个排列。
首先可以将四个数字存入一个数组中,先用sort()函数将其排序,之后用上面提到的函数进行循环即可。但是此题的格式要求比较繁琐,具体处理详见代码。
#include <cstdlib>
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <functional>
#include <list>
#include <deque>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>
#include <memory.h>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#define ll long long
using namespace std;
int main()
{
int a[4], b[4];
// ifstream cin("4.txt");
int T = 0; //判断当前测试例是否为第一组数据,若不是,则应该输出换行符号
while(cin >> a[0] >> a[1] >> a[2] >> a[3])
{
if(!a[0] && !a[1] && !a[2] && !a[3]) //输入的数若全为0则结束输入
break;
T++;
if(T != 1)
cout << endl;
sort(a, a+4); //对a进行排序
while(!a[0]) //用来清除第一位数为0的情况
{
next_permutation(a, a+4);
}
for(int i = 0; i < 4; i++) //初始化b数组,后用来记录前一个排列的值
b[i] = a[i];
int k = 0; //当前数据位置的标识
do{
k++;
if(a[0] != b[0]) //若当前排列的第一个元素不同于上一个排列的第一个元素则输出换行
cout << endl;
else if(k!=1)
cout << " ";
for(int i = 0; i < 4; i++)
{
b[i] = a[i];
cout << a[i];
}
}while(next_permutation(a, a+4));
cout << endl;
}
return 0;
}