排列2 递归-全排列

版权声明:原创文章转载时请注明出处 https://blog.csdn.net/weixin_42856843/article/details/88843634

排列2 递归-全排列

Time limit:1000 ms Memory limit:32768 kB Source: 2007省赛集训队练习赛(2)

描述

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

输入

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

输出

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

Input

1 2 3 4
1 1 2 3
0 1 2 3
0 0 0 0

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

代码

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 4
int a[N];
int main() {
	//freopen("input.txt", "r", stdin);
	int t = 0, tmp;
	while (scanf("%d%d%d%d", &a[0], &a[1], &a[2], &a[3]) && a[0] + a[1] + a[2] + a[3]) {
		if (t)
			cout << endl;
		t = 1;
		int flag = 1;
		do {
			if (a[0] == 0)
				continue;
			if (flag) {
				cout << a[0] << a[1] << a[2] << a[3];
				flag = 0;
			}
			else if (tmp == a[0])
				cout << " " << a[0] << a[1] << a[2] << a[3];
			else {
				cout << endl;
				cout << a[0] << a[1] << a[2] << a[3];
			}
			tmp = a[0];
		} while (next_permutation(a, a + 4));
		cout << endl;
	}
}

代码2

#include <bits/stdc++.h>

#define PI 3.14159265358979383246
#define LL long long
#define INF 0x3f3f3f3f  

#define _for(i, a) for(int i = 0; i < (a); ++i)
#define _rep(i, a, b) for(int i = (a); i < (b); ++i)
#define _forit(a, b) for(a::iterator it = b.begin(); it != b.end(); it++)

using namespace std;

int bitmap[4];
int book[4], t = 0, tt = 0;//t是book的长度,tt是当前目标的个数
int a[4];
vector<string> his;
string x = "0000";
int mm[10] = { 0 };

void arr() {
	if (t == 4) {
		_for(i, 4) x[i] = book[i];
		if (find(his.begin(), his.end(), x) != his.end()) return;
		tt++;
		//if (book[0] == 0) return;
		if (tt != 1) cout << ' ';
		_for(i, 4) {
			cout << book[i];
		}
		his.push_back(x);
		//if (tt % 6 != 0) cout << ' ';
		return;
	}
	_for(i, 4) {
		if (t == 0 && a[i] == 0) continue;
		if (bitmap[i] == 0) {
			bitmap[i] = 1;
			book[t++] = a[i];
			arr();
			t--;
			bitmap[i] = 0;
			if (t == 0 && mm[a[i]] == 0) {
				cout << endl;
				mm[a[i]] = 1;
				tt = 0;
			}
		}
	}
	return;
}

int main()
{
	int q = 0;
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	while (cin >> a[0] >> a[1] >> a[2] >> a[3], a[0] || a[1] || a[2] || a[3]) {
		if (q) cout << endl;
		t = 0; tt = 0;
		while (his.size()) his.erase(his.begin());
		_for(i, 10) mm[i] = 0;
		arr();
		q = 1;
	}
	return 0;
}

本人也是新手,也是在学习中,勿喷

转载请注明出处

欢迎有问题的小伙伴一起交流哦~

猜你喜欢

转载自blog.csdn.net/weixin_42856843/article/details/88843634