<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);
}
POJ1731
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.