ural 1002 Phone Numbers 字典树+dp

http://acm.timus.ru/problem.aspx?space=1&num=1003
题意:

给定一串数字,问这串数字可能代表的单词,若存在多个可能,输出单词数最少的情况,若还是相同输出任意符合的单词。数字转换规则就是根据手机的按键规则。

题解:

我们将所有单词转换成数字,然后保存到字典树中。然后开始dp给定的数字串,dp[i]表示从i开始到最后的数字串最少需要多少个单词构成。dp[i]=min(dp[k+1])(m>k>=i,且[i,k]数字串在字典树中存在)。由于要输出单词,所以用next[i]记录i位置的下个单词位置,id[i]记录i位置前的单词编号。

程序

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>

using namespace std;
int f[27]={2,2,2,3,3,3,4,4,1,1,5,5,6,6,0,7,0,7,7,8,8,8,9,9,9,0};
string ed;
const int maxn=50001*51;
int dp[maxn], id[maxn], next[maxn];
struct trie{
    int ch[maxn][10];
    int val[maxn];
    int sz;
    void init() {sz=0; memset(ch[0], 0, sizeof(ch[0]));}
    int idx(char x) {return f[x-'a'];}
    void insert(string s, int v){
        int u=0, n=s.length();
        for (int i=0; i<n; i++)
        {
            int c=idx(s[i]);
            if (!ch[u][c])
            {
                memset(ch[++sz], 0, sizeof(ch[++sz]));
                val[sz]=0;
                ch[u][c]=sz;
            }
            u=ch[u][c];
        }
        val[u]=v;
    }
    void walk(int x)
    {
        int len=ed.length();
        int u=0;
        for (int i=x; i<len; i++)
        {
            int c=ed[i]-'0';
            if (!ch[u][c]) break;
            u=ch[u][c];
            if (val[u]) if (dp[i+1]<500000 && dp[i+1]+1<dp[x]){
                dp[x]=dp[i+1]+1;
                next[x]=i+1;
                id[x]=val[u];
            }
        }
    }
}t;

string s[50010];
int main()
{
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    int n;
    while (cin>>ed && ed[0]!='-'){
        t.init();
        scanf("%d", &n);
        for (int i=1; i<=n; i++){
            cin>>s[i];
            t.insert(s[i], i);
        }
            int n=ed.length();
        memset(dp, 63, sizeof(dp));
        dp[n]=0;
        for (int i=n-1; i>=0; i--) t.walk(i);
        if (dp[0]>500000) printf("No solution.");
            else{
                int i=0;
                while (1){
                    cout<<s[id[i]];
                    if (i==n) break;
                    printf(" ");
                    i=next[i];
                }
            }
        printf("\n");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值