#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <string.h>
#include <algorithm>
using namespace std;
const int maxn = 50 + 10;
char str[maxn];
int len;
bool solve()
{
len = strlen(str);
int i = len - 1;
while (i > 0 && str[i - 1] >= str[i])
i--;
if (0 == i)
return false;//无后继
int j = len - 1;
while (str[j] <= str[i - 1] && j > i - 1)
j--;
swap(str[i - 1], str[j]);
sort(str + i, str + len);
return true;
}
int main()
{
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
cin >> str;
while (0 != strcmp(str, "#"))
{
if (solve())
cout << str << endl;
else
cout << "No Successor" << endl;
cin >> str;
}
return 0;
}
题目要求即是 求出当前串的按字典序的下一排列组合,设当前串为(p) = p1p2p3...pi-1pi...pn
按字典序求出下一排列的方法如下:
1)由右到左计算最后一个正序的尾下标i: i = max{j | pj-1 < pj ,pj >= pj + 1};
2) 找到pi-1 后面比pi-1大的最后一个数(即比pi-1大的最后一个数)的下标: j = max{ k | k > i ,pi-1 < pk ,pi-1 >= pk + 1}
3) 互换pi-1 与 pj,得到 p1...pi-2pjpipi+1...pj-1pi-1pj+1...pn
4) 将pj后面的数按递增顺序排列,得到 下一排列
如:2763541
1.找到最后一个正序35;
2.找到在3后面比其大的最后一个数4
3.互换3 与 4 的位置 2764531
4.把4后面的字符串按升序排列 2764135
poj1146: