洛谷P1245電話號碼
阿新 • • 發佈:2018-12-18
題目: 電話機上每一個數字下面都寫了若干個英文字母。分佈如下:
1~abc
2~def
3~ghi
4~jkl
5~mn 6~opq
7~rst
8~uvw
9~xyz
現在給定一個單詞表和一串數字密碼,請你用單詞表中的單詞翻譯這個密碼。
輸入格式: 第一行為一個正整數N表示單詞表中單詞的個數(N≤100);
第二行為一個長度不超過100的數字串,表示密碼;
接下來的N行,每行一個長度不超過20的單詞,表示單詞表。
輸出格式: 僅一行,表示翻譯後的原文,如果密碼無法翻譯,則輸出“No Solutions!”,如果密碼有多種翻譯方式,則輸出任意一種即可。
輸入樣例: 8 73373711664 thi shs this is b a boo k 輸出樣例:
說明 僅一行,表示翻譯後的原文,如果密碼無法翻譯,則輸出“No Solutions!”,如果密碼有多種翻譯方式,則輸出任意一種即可。
注意: 1、末尾空格有影響 2、當一個全域性變數在不停變換時,可換成函式引數
#include<bits/stdc++.h> #define maxn 110 using namespace std; int n,a[maxn],zx,zc,tot=0,q,p=0,m[maxn]; char w[maxn][25]; char s[10][5],ans[2010]; void work(int x,int zc,int zx){ if(x==q+1){ if(zc==0){ if(ans[tot]==' ') tot--; for(int i=1;i<=tot;i++)printf("%c",ans[i]); p=1; } return ; } for(int i=1;i<=3;i++){ if(zc!=0){ if(s[a[x]][i]==w[zc][zx]){ ans[++tot]=s[a[x]][i]; if(zx==m[zc]){ ans[++tot]=' '; work(x+1,0,1); tot--; } else work(x+1,zc,zx+1); tot--; if(p==1)return ; } } else{ for(int j=1;j<=n;j++){ if(s[a[x]][i]==w[j][zx]){ ans[++tot]=s[a[x]][i]; if(zx==m[j]){ ans[++tot]=' '; work(x+1,0,1); tot--; } else work(x+1,j,zx+1); tot--; if(p==1)return ; } } } } return ; } int main(){ memset(s,0,sizeof(s)); char x; string h; scanf("%d\n",&n); scanf("%c",&x); while(x>='0'&&x<='9'){ a[++tot]=x-'0'; scanf("%c",&x); } q=tot; char g='a'; for(int i=1;i<=9;i++){ if(i==5){ for(int j=1;j<=2;j++){ int g1=g; s[i][j]=g1; g++; } } else for(int j=1;j<=3;j++){ int g1=g; s[i][j]=g1; g++; } } for(int i=1;i<=n;i++){ cin>>h; m[i]=h.length(); for(int j=0;j<m[i];j++)w[i][j+1]=h[j]; } tot=0; work(1,0,1);//數字串的位置,單詞的序號,對應單詞的位置 if(p==0)printf("No Solutions!\n"); return 0; }