3997 - 蓝桥5:排列序数
时间限制 : 1 秒
内存限制 : 128 MB
如果用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 cedab
输出格式
11 70
C++解答
#include <iostream> #include <algorithm> #include <map> #include <vector> #include <string> using namespace std; const int N = 10; int fact[N + 1]; int Solve(string word) { int vec[N + 1] = { 0 }; char src, dest; int i, j; reverse(word.begin(), word.end());//简单翻转一下字符串,方便下面做处理而已 for (i = 0; i < word.length(); i++) { src = word[i]; for (j = 0; j < i; j++) { dest = word[j]; if (dest <src) vec[i]++; } } int sum = 0; for (i = 0; i < word.length(); i++) { sum += vec[i] * fact[i]; } return sum; } int main() { fact[0] = 1; for (int i = 1; i <= N; i++) { fact[i] = i * fact[i - 1]; } string word; while (cin >> word) { cout << Solve(word) << endl; } //system("pause"); return 0; }