題意
題意很明確,就是給定一個整數,
INPUT
156
330
27711
OUTPUT
165
0
71127
思路
可以等價爲 求這個數的下一個排列;
C++ STL的一個庫函數next_permutation()
要方便很多。
下面簡單介紹一下:
STL中的 next_permutation()
可以直接求出下一個排列
使用:bool next_permutation(_Biter,_Biter,[compaer)
參數就與sort()
一樣,若不存在下一個排列,則返回 false,反之爲true,並且對_biter 做出修改;
例如:
對序列 {a, b,c},按照字典序列,固定a之後,a比bc都小,c比b大,它的下一個序列即爲{a, c, b},而{a, c, b}的上一個序列即爲{a, b, c},同理可以推出所有的六個序列爲:{a, b, c}、{a, c, b}、{b, a, c}、{b, c, a}、{c, a, b}、{c, b, a},其中{a, b, c}沒有上一個元素,{c, b, a}沒有下一個元素。
同樣數字一樣,其實第三個參數,就是compare, 只要可以比較的數據類型,包括 自定義類, 都可以使用這個函數來求得下一個排列。
同樣:除了有下一個排列之外,也有上一個排列函數pre_permutation()
,用法完全一樣;
代碼
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
int main()
{
char x[10];
while(cin>>x)
{
if(next_permutation(x,x+strlen(x)))
cout<<x<<endl;
else cout<<0<<endl;
}
}next_permutation()