题目:
字符串字母按字典序递增的为合法的,给出一个字符串问是第几个(从1开始计数)。
非法字符串输出"0"。
思路:
假设字符串长度为len,长度小于len的累加即可,对于长度等于len的 ,假设对于第pos位,枚举这一位合法的字符x,给答案加上c[26-x-1][len-pos-1]
代码:
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<algorithm>
#include<ctime>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<list>
#include<numeric>
using namespace std;
#define LL long long
#define ULL unsigned long long
#define INF 0x3f3f3f3f3f3f3f3f
#define mm(a,b) memset(a,b,sizeof(a))
#define PP puts("*********************");
template<class T> T f_abs(T a){ return a > 0 ? a : -a; }
template<class T> T gcd(T a, T b){ return b ? gcd(b, a%b) : a; }
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
// 0x3f3f3f3f3f3f3f3f
LL c[30][30];
void Init(){
for(int i=0;i<=26;i++)
c[i][0]=c[i][i]=1;
for(int i=1;i<=26;i++)
for(int j=1;j<i;j++)
c[i][j]=c[i-1][j-1]+c[i-1][j];
}
char str[20];
int main(){
Init();
while(~scanf("%s",str)){
int len=strlen(str);
int k=0;
for(;k<len-1;k++)
if(str[k]>=str[k+1])
break;
if(k<len-1){
printf("0\n");
continue;
}
LL ans=0;
for(int i=1;i<len;i++)
ans+=c[26][i];
int pos=0;
for(int i=0;i<len;i++){
for(int j=pos;j<str[i]-'a';j++){
ans+=c[26-j-1][len-i-1];
}
pos=str[i]-'a'+1;
}
printf("%lld\n",ans+1);
}
return 0;
}
本文介绍了一种算法,用于计算给定字符串在其所有可能排列中按字典序的排名(从1开始计数)。如果字符串不符合字典序递增规则,则输出0。文章通过组合数学原理,提供了一个高效的解决方案。
225

被折叠的 条评论
为什么被折叠?



