【递归与递推】电话号码

问题 L: 【递归与递推】电话号码

题目描述

电话机上每一个数字下面都写了若干个英文字母。分布如下:
      1~abc
      2~def
      3~ghi
      4~ikl
      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

样例输出

thi shs b boo k
#include <bits/stdc++.h>
using namespace std;
int n,cnt = 1;
struct word {
    string s,l;
} a[101];
stack<int> sta;
string o;
stack<int>p;
void slove(int y,int x) {
    if(!cnt) return ;
    if(y == o.size()) {
        while(!p.empty()) {
            int x = p.top();
            sta.push(x);
            p.pop();
        }
         int x = sta.top();
            sta.pop();
            cout<<a[x].s;
        while(!sta.empty()){
            int x = sta.top();
            sta.pop();
            cout<<" "<<a[x].s;
        }
        cout<<endl;
            cnt = 0;
            return ;
    }
    int flag;
    for(int i = x; i < n; i++) {
        flag = 1;
        for(int j = 0; j < a[i].l.size(); j++) {
            if(a[i].l[j] != o[y+j]) {
                flag = 0;
                break;
            }
        }
        if(flag) {
            p.push(i);
//            cout<<"+"<<a[i].s<<endl;
            slove(y+a[i].l.size(),0) ;
        }
    }
 
    if(!flag&&cnt) {
        if(p.empty()) {
            printf("No Solutions!\n");
            return ;
        } else {
            int x = p.top();
//            cout<<"-"<<a[x].s<<endl;
            p.pop();
            slove(y-a[x].l.size(),x+1);
        }
    }
}
int main() {
 
    //freopen("data.in.txt","w",stdout);
    cin>>n;
    cin>>o;
    while(!p.empty())
        p.pop();
    for(int i = 0; i < n; i++) {
        cin>>a[i].s;
        for(int j = 0; j < a[i].s.size(); j++) {
            int m;
            if(a[i].s[j] >= 'o')
                m = (a[i].s[j] + 1 - 'a')/3 + 1;
            else   m = (a[i].s[j]  - 'a')/3 + 1;
            a[i].l += (m + '0');
 
        }
    }
    slove(0,0);
    return 0;
}
View Code

 

posted on 2016-07-04 21:57  disppr  阅读(342)  评论(0编辑  收藏  举报