我排第几个
时间限制:
1000 ms | 内存限制:
65535 KB
难度:
3
-
描述
-
现在有"abcdefghijkl”12个字符,将其所有的排列中按字典序排列,给出任意一种排列,说出这个排列在所有的排列中是第几小的?
-
第一行有一个整数n(0<n<=10000);
随后有n行,每行是一个排列;
输出
- 输出一个整数m,占一行,m表示排列是第几位; 样例输入
-
3
-
abcdefghijkl
-
hgebkflacdji
-
gfkedhjblcia
样例输出
-
1
-
302715242
-
260726926
-
康托展开
-
输入
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
long int factory[]={1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,479001600};//阶乘表
long Contor(char str[], int n)
{
long result = 0;
for(int i = 0; i < n; i++)
{
int counted = 0;
for(int j = i+1; j < n; j++)
{
if(str[i] > str[j]) //当前未出现的元素中是排在第几个
++counted;
}
result += counted*factory[n-i-1];
}
return result+1; //从0开始
}
int main()
{
char str[100];
int n;
scanf("%d", &n);
while(n--){
cin >> str;
cout << Contor(str, strlen(str))<<endl;;
}
return 0;
}