HDU-1716 排列2

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1716

The title

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

思路

全排列。注意题目要求的格式,我一度认为这是一道格式题。在解法上我们可以选择循环嵌套模拟或者使用库内自带函数 ”next_permutation()“,这个函数的详细用法可见 C++ Primer第778页 。

虽然我是使用函数写的,但我仅是第一次使用这个函数做一个尝试,并不推荐,因为这题的格式要求很多,所以建议直接循环嵌套模拟,在模拟的过程中就可以对格式做出调整,轻松很多。

Code

#include <bits/stdc++.h>
#include <algorithm>
#define PI 3.141593
#define INF 0x3f3f3f3f
#define Best 0x7fffffff

using namespace std;

int a[700000];

int main() {
	ios::sync_with_stdio(false);
	//int n;
	int n, p = 0, s, k = 0;
	while (cin >>a[0]>>a[1]>>a[2]>>a[3], a[0], a[1], a[2],a[3]) {
		/*for (int i = 0; i < 4; i++) {
			cin >> a[i];
		}*/
		//p = 0;
		/*if (a[0] == 0 && a[1] == 0 && a[2] == 0 && a[3] == 0) {
			break;
		}*/
		sort(a, a + 4);
		/*if (a[0] != 0) {
			cout << a[0] << a[1] << a[2] << a[3] << " ";
		}*/
		if (p != 0) {
			cout << endl;
		}
		p++;
		int x = 0;
		int m = a[0], s = 1;
		if (a[k] == 0) {
			m = a[k++];
		}
		do {
			/*for (int i = 0; i < 4; ++i)
				cout << a[i];
			cout << " ";*/
			if (a[0] == 0) {
				continue;
			}
			//else {
				/*for (int i = 0; i < 4; ++i)
					cout << a[i];
				cout << " ";*/
				//}
			if (s) {
				cout << a[0] << a[1] << a[2] << a[3] ;
				s = !s;
			}
			 else if (a[0] == m) {
				cout << " " << a[0] << a[1] << a[2] << a[3];
			}
			else {
				cout << endl;
				cout  << a[0] << a[1] << a[2] << a[3];
				//cout << endl;
			}
			m = a[0];
			//s = a[0];
					/*if (s == a[0])
						cout << a[0] << a[1] << a[2] << a[3];
					else {
						cout << endl;
						cout << a[0] << a[1] << a[2] << a[3];
					}
				s = a[0];*/
			//cout << endl;
		} while (next_permutation(a, a + 4));
		cout << endl;
	}
	//猝不及防的周末训练打乱了我的计划也打乱了我的心,同时也帮我打开了C++ Primer第778页 :)代码十分钟格式一小时
	return 0;
}
posted @ 2020-09-03 07:50  琦桢  阅读(206)  评论(0编辑  收藏  举报