字典序問題 演算法實現題1-2
阿新 • • 發佈:2020-07-20
字典序問題 演算法實現題1-2
題意
《計算機演算法設計與分析》第8頁。
在資料加密和資料壓縮中需要對特殊的字串進行編碼。給定的字母表由26個小寫字母組成。該字母表產生的升序字串是指字串中字母從左到右出現的次序與字母在字母表中出現的次序相同,且每個字元最多出現1次。例如,a,b,ab,bc, xyz等都是升序字串。
他們有對應的序號:
1 | 2 | …… | 26 | 27 | 28 | …… |
---|---|---|---|---|---|---|
a | b | …… | z | ab | ac | …… |
題解思路
程式碼實現
#include<bits/stdc++.h> using namespace std; const int MAXN = 26; const int MAXL = 6; int ff[MAXN+1][MAXL+1]; int gg[MAXL+1]; //多加了一個記憶化 int f(int ch,int len) { int index=0; if(ff[ch][len]!=0) return ff[ch][len]; if(len==1) return ff[ch][1] = 1; for(int i=ch+1; i<=27-len; i++) index+=f(i,len-1); return index; } int g(int len) { int index=0; if(gg[len]!=0) return gg[len]; for(int ch=0;ch<=26-len;ch++) index+=f(ch,len); return index; } int main() { int i,k; int ch; char str[7]; //先進行初始化 fill(ff[0], ff[0]+MAXN*MAXL, 0); fill(gg, gg+MAXL, 0); while(scanf("%s", str)!=EOF){ int pos=0; for(i=1;i<strlen(str);i++) pos+=g(i); for(ch=0;ch<str[0]-'a';ch++) pos+=f(ch,strlen(str)); for(k=1; k<strlen(str); k++) for(ch=str[k-1]-'a'+1; ch<str[k]-'a'; ch++) pos+=f(ch,strlen(str)-k); printf("位置是:%d\n",pos+1); } return 0; }