习题8-7 生成排列(Generating Permutations, UVa11925)

该博客介绍了一种使用冒泡排序思想解决UVa11925问题的方法,通过调整冒泡排序过程来生成从123到213等所有可能的排列。文章包含C++代码实现,并进行了调试输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:
冒泡排序的思想。
题目要求从123 -> 到213,可以转换一下 从无序到有序可以用冒泡解决
123 -> 213, 213变为123则123->213,同理123 -> 231等价于312 -> 123。
注意处理多余的2操作即可。
#include <set>
#include <map>
#include <ctime>
#include <cmath>
#include <stack>
#include <queue>
#include <deque>
#include <cstdio>
#include <string>
#include <vector>
#include <cctype>
#include <sstream>
#include <utility>
#include <cstring>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <algorithm>
#define SF(a) scanf("%d", &a)
#define PF(a) printf("%d\n", a)  
#define SFF(a, b) scanf("%d%d", &a, &b)  
#define SFFF(a, b, c) scanf("%d%d%d", &a, &b, &c)
#define SFFFF(a, b, c, d) scanf("%d%d%d%d", &a, &b, &c, &d)
#define CLEAR(a, b) memset(a, b, sizeof(a))
#define IN() freopen("in.txt", "r", stdin)
#define OUT() freopen("out.txt", "w", stdout)
#define FOR(i, a, b) for(int i = a; i < b; ++i)
#define ALL(a) (a).begin(), (a).end()
#define SZ(a) (int)(a).size()
#define PB push_back
#define LL long long
#define mod 10007
#define inf 107
#define eps 1e-12
using namespace std;
int buf[20];
int read() {
	int x = 0; char ch = getchar(); bool f = 0;
	while (ch < '0' || ch > '9') { if (ch == '-') f = 1; ch = getchar(); }
	while (ch >= '0' && ch <= '9') x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
	return f ? -x : x;
}
void write(int x) {
	if (!x) { putchar(48); return; }
	int l = 0; if (x < 0) putchar('-'), x = -x;
	while (x) buf[++l] = x % 10, x = x / 10;
	while (l) putchar(buf[l--] + 48);
}
//-------------------------chc------------------------------//
const int maxn = 305;
const int maxm = 2 * 305 * 305;
int n;
int a[maxn];
int v[maxm], sz = 0;

void debug() {
	int t[maxn];
	FOR(i, 0, n) t[i] = i + 1;
	int cur = 0;
	FOR(i, 0, sz) {
		if (v[i] == 1) swap(t[cur % n], t[(cur + 1) % n]);
		else cur++;
	}
	FOR(i, 0, n) printf("%d", t[(cur + i) % n]);
	cout << endl;
}

int main() {
	while (~SF(n) && n) {
		sz = 0;
		int x;
		FOR(i, 0, n) x = read(), a[x - 1] = i + 1;
		int cnt = 0;
		for (int i = n - 1; i > 0; --i) {
			bool changed = false;
			FOR(j, 0, i) {
				if (a[j] > a[j + 1]) {
					cnt %= n;
					FOR(k, 0, cnt) v[sz++] = 2;
					cnt = 0;
					swap(a[j], a[j + 1]);
					changed = true;
					v[sz++] = 1;
				}
				cnt++;
			}
			for (int j = i; j < n; ++j) cnt++;
			if (!changed) break;
		}
		cnt %= n;
		FOR(k, 0, cnt) v[sz++] = 2;
		FOR(i, 0, sz) printf("%d", v[i]);
		putchar('\n');
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值