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;
}