链接http://acm.hdu.edu.cn/showproblem.php?pid=1716
Problem Description
Ray又对数字的列产生了兴趣:
现有四张卡片,用这四张卡片能排列出很多不同的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
手写或者使用C++的全排列都可以,格式是最坑的,手写的格式错了几遍才对;
全排列函数:
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int a[5], flag1 = 0;
while (cin >> a[1] >> a[2] >> a[3] >> a[4])
{
if (a[1] == 0 && a[2] == 0 && a[3] == 0 && a[4] == 0)
break;
int flag = 1, front; //用front来记录首数字
if (flag1)cout << endl; flag1 = 1; //最后一组测试数据不用换行用这个来控制
do{
if (a[1] == 0) //首位为0跳过
continue;
if (flag == 1)
cout << a[1] << a[2] << a[3] << a[4], flag = 0;
else if (a[1] == front)
cout << " " << a[1] << a[2] << a[3] << a[4];
else cout << endl << a[1] << a[2] << a[3] << a[4], front = a[1];
front = a[1];
} while (next_permutation(a + 1, a + 5)); //stl的全排列
cout << endl;
}
return 0;
}
手写:
#include<iostream>
#include<algorithm>
#include<string.h>
#include<map>
using namespace std;
map<int, int>mp;
int a[10], b[10], c[10];
int front, flag = 1, flag1 = 0;
void dfs(int d){
if (d == 5){
int sum = 0;
for (int i = 1; i <= 4; i++)
sum = sum * 10 + b[i];
if (mp[sum] || b[1] == 0)return; //map是为了防止因为输入的数字有重复而导致的重复
mp[sum] = 1;
if (flag == 1)
cout << b[1] << b[2] << b[3] << b[4], flag = 0, front = b[1];
else
if (b[1] == front)
{
cout << " " << b[1] << b[2] << b[3] << b[4];
}
else
cout << endl << b[1] << b[2] << b[3] << b[4], front = b[1];
}
else{
for (int i = 1; i <= 4; i++)
if (c[i] == 0)
b[d] = a[i], c[i] = 1, dfs(d + 1), c[i] = 0;
}
}
int main(){
while (cin >> a[1] >> a[2] >> a[3] >> a[4] && (a[1] || a[2] || a[3] || a[4]))
{
if (flag1)
cout << endl; //最后一组样例没有换行
flag1 = 1;
flag = 1;
memset(c, 0, sizeof c);
dfs(1);
cout << endl;
}
return 0;
}