题目描述
如果用 a b c d 这 4 个字母组成一个串,有 4!=24 种,如果把它们排个序,每个串都对应一个序号:
abcd 0
abdc 1
acbd 2
acdb 3
adbc 4
adcb 5
bacd 6
badc 7
bcad 8
bcda 9
bdac 10
bdca 11
cabd 12
cadb 13
cbad 14
cbda 15
cdab 16
cdba 17
⋯⋯
现在有不多于 10 个两两不同的小写字母,给出它们组成的串,你能求出该串在所有排列中的序号吗?
输入描述
输入一行,一个串。
输出描述
输出一行,一个整数,表示该串在其字母所有排列生成的串中的序号。注意:最小的序号是 0。
输入输出样例
示例
输入
bdca
输出
11
知识解读:
序列全排列的函数:(当不存在下一个排列时,函数返回false,否则返回true)
next_permutation(start,end)求的是当前排列的下一个排列
prev_permutation(start,end)求的是当前排列的上一个排列
代码如下:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string s,temp;
int num=0;
cin >> s; temp=s;
sort(temp.begin(),temp.end()); //把temp排序一下,变成abcd...
do{
//cout<<a<<endl;
if(temp==s){
cout << num <<endl;
break;
}
num++;
}while(next_permutation(temp.begin(),temp.end())); //这时temp的排序已经修改
//计算序列全排列的函数next_permutation(start,end)是求当前排列的下一个排列
//当当前序列不存在下一个排列时,函数返回false,否则返回true
return 0;
}