给定数字,翻译出对应的名字,在有限的名字字典中寻找最终可用正确的名字。
这道题有多种方法,我这里介绍三种:
1. 这是我自己想出来的方法,可是TLE。想法很简单就是,翻译出所有对应的名字,然后依次考察改名字是否在字典中。
我把dict.txt处理成了map,这样在查询的时候就比较方便了。但是显然数字越长,可能情况越多。
2. luogu上看来的,直接把dict.txt处理成数字,然后直接把输入数字来比较,暴力遍历即可,很聪明的解法。
3. 官方题解之一,很精彩,构建字母到数字映射的map[],对给定数字数组,依次遍历dict.txt中每个name,对每个名字每位翻译再比较,不对直接下一个。
1
/*
PROG:namenum
ID:imking022
LANG:C++
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int n;
map<string,int> mapp;
void ini(){
ifstream fin ("dict.txt");
string ss;
while(fin>>ss){
mapp[ss]++;
}
}
char reff[10][4] = { " "," ","ABC","DEF","GHI",
"JKL","MNO","PRS",
"TUV","WXY"
};
int main(void){
freopen("namenum.out","w",stdout);
freopen("namenum.in","r",stdin);
string num,str;
cin>>num;
ini();
n = num.size();
int sum = pow(3,n),t,bar,count=0;
int *cot = (int *) malloc((n+1)*sizeof(int));
for(int i=0;imemset(cot,0, ((n+1)*sizeof(int))) ;
t = i;
for(int j=n;j>=1;j--){
cot[j] = t%3;
t-=cot[j];
t/=3;
}
str = "";
for(int j=1;j<=n;j++){
bar=num[j-1]-'0';
str += reff[ bar ][ cot[j] ];
}
if(mapp[str]>0) {
cout<if(count == 0) cout<<"NONE"<return 0;
}
2
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int n;
char reff[]="22233344455566670778889990";
string str,s[4700],d[4700];
void ini(){
ifstream fin ("dict.txt");
string ss;
int snum;
n=0;
while(fin>>ss){
s[n] = ss;
d[n] = ss;
n++;
}
for(int i=0;ifor(int j=0;j'A' ];
}
}
int main(void){
freopen("namenum.out","w",stdout);
freopen("namenum.in","r",stdin);
cin>>str;
ini();
bool ok = false;
for(int i=0;iif(s[i] == str) {
cout<true;
}
}
if(!ok) cout<<"NONE"<return 0;
}
3 这个太优秀了
#include
#include
#include
int main() {
FILE *in = fopen ("namenum.in", "r");
FILE *in2 = fopen ("dict.txt", "r");
FILE *out = fopen ("namenum.out","w");
int nsolutions = 0;
int numlen;
char word[80], num[80], *p, *q, map[256];
int i, j;
map['A'] = map['B'] = map['C'] = '2';
map['D'] = map['E'] = map['F'] = '3';
map['G'] = map['H'] = map['I'] = '4';
map['J'] = map['K'] = map['L'] = '5';
map['M'] = map['N'] = map['O'] = '6';
map['P'] = map['R'] = map['S'] = '7';
map['T'] = map['U'] = map['V'] = '8';
map['W'] = map['X'] = map['Y'] = '9';
fscanf (in, "%s",num);
numlen = strlen(num);
while (fscanf (in2, "%s", word) != EOF) {
for (p=word, q=num; *p && *q; p++, q++) {
if (map[*p] != *q)
break;
}
if (*p == '\0' && *q == '\0') {
fprintf (out, "%s\n", word);
nsolutions++;
}
}
if (nsolutions == 0) fprintf(out,"NONE\n");
return 0;
}