题目信息:http://acm.nyist.net/JudgeOnline/problem.php?pid=139
现在有"abcdefghijkl”12个字符,将其所有的排列中按字典序排列,给出任意一种排列,说出这个排列在所有的排列中是第几小的?
3
abcdefghijkl
hgebkflacdji
gfkedhjblcia
1
302715242
260726926
题目分析:
本题的家吗问题,在《算法入门经典》中有解答,对于每一个字符s,若在其后有k个字符小于s,则当前的序列的排序会增大k*f[12-i]。
AC代码:
/**
*给出一个字符串,仅由a~l组成,每个出现一次,求给出字符串的字典序大小
*对于每一个字符s,若在其后有k个字符小于s,则当前的序列的排序会增大k*f[12-i]
*其中f是每个数的阶乘,i为s的位置,因此只需模拟每一位进行比较即可。
*/
#include<iostream>
#include<cstdio>
#include<map>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
#include<vector>
#include<stack>
#include<cstdlib>
#include<cctype>
#include<cstring>
#include<cmath>
using namespace std;
int main()
{
long long f[15];
f[1]=1;
for(int i=2;i<=12;i++){
f[i]=f[i-1]*i;
}
char s[15]; int t;
scanf("%d",&t);
while(t--){
scanf("%s",s+1);
long long sum=0;
for(int i=1;i<=12;i++){
int k=0;
for(int j=i+1;j<=12;j++){
if(s[i]>s[j]) k++;
}
sum+=f[12-i]*k;
}
printf("%lld\n",sum+1);
}
return 0;
}
原文地址:http://blog.csdn.net/fool_ran/article/details/42065491