原题:
Among the large Wisconsin cattle ranchers, it is customary to brand cows with serial numbers to please the Accounting Department. The cow hands don’t appreciate the advantage of this filing system, though, and wish to call the members of their herd by a pleasing name rather than saying, “C’mon, #4734, get along.”
Help the poor cowhands out by writing a program that will translate the brand serial number of a cow into possible names uniquely associated with that serial number. Since the cow hands all have cellular saddle phones these days, use the standard Touch-Tone(R) telephone keypad mapping to get from numbers to letters (except for “Q” and “Z”):
2: A,B,C 5: J,K,L 8: T,U,V3: D,E,F 6: M,N,O 9: W,X,Y4: G,H,I 7: P,R,S
Acceptable names for cattle are provided to you in a file named “dict.txt”, which contains a list of fewer than 5,000 acceptable cattle names (all letters capitalized). Take a cow’s brand number and report which of all the possible words to which that number maps are in the given dictionary which is supplied as dict.txt in the grading environment (and is sorted into ascending order).
For instance, the brand number 4734 produces all the following names:
GPDG GPDH GPDI GPEG GPEH GPEI GPFG GPFH GPFI GRDG GRDH GRDI
GREG GREH GREI GRFG GRFH GRFI GSDG GSDH GSDI GSEG GSEH GSEI
GSFG GSFH GSFI HPDG HPDH HPDI HPEG HPEH HPEI HPFG HPFH HPFI
HRDG HRDH HRDI HREG HREH HREI HRFG HRFH HRFI HSDG HSDH HSDI
HSEG HSEH HSEI HSFG HSFH HSFI IPDG IPDH IPDI IPEG IPEH IPEI
IPFG IPFH IPFI IRDG IRDH IRDI IREG IREH IREI IRFG IRFH IRFI
ISDG ISDH ISDI ISEG ISEH ISEI ISFG ISFH ISFI
As it happens, the only one of these 81 names that is in the list of valid names is “GREG”.
Write a program that is given the brand number of a cow and prints all the valid names that can be generated from that brand number or “NONE” if there are no valid names. Serial numbers can be as many as a dozen digits long.
题意:
给定一个字典文件(dict.txt),里面包含合法的名字。
根据九宫格输入法的格式输入数字,
2: A,B,C 5: J,K,L 8: T,U,V
3: D,E,F 6: M,N,O 9: W,X,Y
4: G,H,I 7: P,R,S
找出可以与输入的数字匹配的合法名字。
题解:
用一个数组key保存每个英文字母对应的数字,遍历字典,(在字符串长度上做一个优化,长度不等的不处理。)将字符串转换成输入的数字序列进行比对。完全遍历字典文件可能会超时。
代码:
/* ID:newyear111 PROG: namenum LANG: C++ */#include <iostream>
#include <fstream>
#include <string>
#include<map>
#include<algorithm>
using namespace std;
const int N=10010;char key[28]= {
'2','2','2','3','3','3','4','4','4','5','5','5','6','6','6','7','0','7','7','8','8','8','9','9','0'};int main()
{ifstream fin("namenum.in");ofstream fout("namenum.out");ifstream fin2("dict.txt");string str,s,temp;int n;fin>>str;n=str.length();bool flag=false;while(fin2>>s){if(s.length()!=n)continue;temp="";for(int i=0;i<n;i++){temp+=key[s[i]-'A'];}if(temp==str){fout<<s<<endl;flag=true;}}if(!flag){fout<<"NONE"<<endl;}fin.close();fout.close();fin2.close();return 0;
}