这题就是根据编号与字母的对应表找出符合条件的名字。
很明显这题如果排列出所有的可能,再与字典进行对比,肯定会超时。
所以肯定需要剪枝。
一开始,我是用一个数组记住26个字母作为首字母第一次出现在字典中位置(因为字典是按字典序排列的),这样来减少每次遍历的次数,但是这样依然会超时。
然后,我就在排列过程中判断,如果已经排列好的字符串不是字典中任何一个名字的子串,就不继续排列,直接剪枝,通过这个能减掉大量的枝。
/*
ID: 13913351
LANG: C++
TASK: namenum
*/
#include<iostream>
#include<string.h>
#include<fstream>
#define cin fin
#define cout fout
using namespace std;
const int N=10;
string inputfile = "namenum.in";
string outputfile = "namenum.out";
ifstream fin(inputfile.c_str());
ofstream fout(outputfile.c_str());
char lett[N][4]={{'A','B','C'},{'D','E','F'},{'G','H','I'},{'J','K','L'},{'M','N','O'},{'P','R','S'},{'T','U','V'},{'W','X','Y'}};
char dict[5000][15];
int length;
char num[15];
char name[15];
int flag[27];
bool tag=false;
void input()
{
ifstream in("dict.txt");
memset(flag,0,sizeof(flag));
int i=0;
while(1)
{
in>>dict[i];
if(flag[dict[i][0]-'A']==0)
{
flag[dict[i][0]-'A']=i;//记住位置
}
if(strlen(dict[i])==0)break;
i++;
}
flag[26]=length;
length=i;
}
void dfs(int step)
{
if(step>0)//剪枝
{
bool mark=false;
for(int i=flag[name[0]-'A'];i<flag[name[0]-'A'+1];i++)
{
mark=true;
int j;
for(j=0;j<step;j++)
{
if(name[j]!=dict[i][j])
{
mark=false;
break;
}
}
if(mark)break;
}
if(mark==false)return ;
}
if(step==strlen(num))
{
name[step]='\0';
for(int i=flag[name[0]-'A'];i<flag[name[0]-'A'+1];i++)
{
if(strcmp(name,dict[i])==0)cout<<name<<endl;
}
tag=true;
return ;
}
for(int i=0;i<3;i++)
{
name[step]=lett[num[step]-'0'-2][i];
dfs(step+1);
}
}
int main()
{
input();
// cout<<length<<endl;
cin>>num;
dfs(0);
if(tag==false)cout<<"NONE"<<endl;
return 0;
}