UVa - 11925 - Generating Permutations



判断前两个,如果第一个大于第二个(但当第一个等于n,第二个等于1的时候不可以)交换前两个,否则执行操作2的逆操作,把最后一个拿到第一个位置。。。

最后把操作顺序逆着打印出来就OK了。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <stack>
#include <queue>
#include <bitset> 
#include <cassert> 
#include <cmath>
#include <functional>

using namespace std;

vector<int> permu, ans;
int  n;

void operate()
{
	while (1) {
		if (permu[0] == 1) { // 判断是否完成了
			bool ok = true;
			for (int i = 0; i < n; i++) {
				if (permu[i] != i + 1) {
					ok = false;
				}
			}
			if (ok) {
				return;
			}
		}

		// 注意当第一个大于第二个的时候换,但是如果第一个等于n第二个等于1是不能换的
		if (permu[0] > permu[1] && !(permu[0] == n && permu[1] == 1)) {
			ans.push_back(1);
			swap(permu[0], permu[1]);
		}
		else {
			ans.push_back(2);
			permu.insert(permu.begin(), permu[n - 1]);
			permu.erase(permu.end() - 1);
		}
	}
}

int main()
{
	ios::sync_with_stdio(false);
	while (cin >> n && n) {
		int t;
		permu.clear();
		ans.clear();
		for (int i = 0; i < n; i++) {
			cin >> t;
			permu.push_back(t);
		}
		operate();
		// 逆着输出ans
		for (int i = ans.size() - 1; i >= 0; i--) {
			cout << ans[i];
		}
		cout << endl;
	}

	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值