POJ1731

<pre name="code" class="cpp">#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int func(string& input,int start,int last) 
{
	int left = start;
	int right = last;
	char key = input[left];
	while (left < right) {
		while (left < right && input[right] >= key)
			-- right;
		swap(input[left],input[right]);
		while (left < right && input[left] <= key)
			++ left;
		swap(input[left],input[right]);
	}
	return left;
}
void quicksort(string& input,int start,int last)
{
	if (start < last) {
		int q = func(input,start,last);
		quicksort(input,start,q - 1);
		quicksort(input,q + 1,last);
	}
}
void permutation (string input)
{
	cout<<input<<"\n";//输出原序列(升序)
	while (true) {
		int idx = -1;
		for (int i = input.size() - 1; i >= 1; -- i) {
			if (input[i - 1] < input[i]) { //从后面向前搜索,找到第一个升序
				idx = i - 1;//记下索引
				break;
			} 
		}
		if ( idx == -1 ) break; //如果还是-1就证明意识降序,所有排列都已输出,就跳出循环
		char Z = 'z';
		int temp = 0;
		//从后向前搜,找到比input[idx]大的最小的那个字符
		for (int j = input.size() - 1;j > temp; -- j) {
			if (input[j] <= input[idx]) continue;
			if (input[j] < Z) {
				temp = j;
				Z = input[j];
			}
		}
		swap(input[idx],input[temp]);//交换这两个字符
		int len = input.size() - 1 - idx;
		//逆序input[idx]之后的字符
		for (int k = 1; k <= (len/2); ++ k) {
			swap(input[idx+k],input[input.size()-k]);
		}
		cout<<input<<"\n";
	}
}

int main ()
{
	string str = "";
	cin>>str;
	quicksort(str,0,str.size() - 1);
	permutation(str);
}




                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值