一个字母只对应一个数字,从字典中读入一个单词,把它转化成唯一对应的数字,看它是否与给出的数字匹配,时间规模是5000*12=6e4,空间规模是常数,而且编程复杂度较低.
一开始,我把对应的数字设为int,后来发现,溢出了,囧。改成string字符数组就好了
/* ID:twd30651 PROG:namenum LANG:C++ */ #include<iostream> #include<fstream> #include<string.h> #include<string> using namespace std; // 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 // a b c d e f g h i j k l m n o p q r s t u v w x y int m[]={2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9}; typedef struct node { char name[20]; string num; }node; node names[5000]; int nl; void generate() { for(int i=0;i<nl;++i) { names[i].num=""; for(unsigned j=0;j<strlen(names[i].name);++j) { if(names[i].name[j]=='Q')continue; names[i].num+=m[names[i].name[j]-'A']+'0'; } } } int main(int argc,char *argv[]) { freopen("namenum.in","r",stdin); freopen("namenum.out","w",stdout); FILE *f=fopen("dict.txt","r"); int i=0; while(fscanf(f,"%s",names[i].name)==1) { if(names[i].name[0]=='Z')break; i++; } string NUM; cin>>NUM; nl=i; generate(); int flag=0; for(int i=0;i<nl;++i) { if(names[i].num==NUM){ flag=1; printf("%s\n",names[i].name); } } if(flag==0) printf("NONE\n"); return 0; }
USACO 1.2 Name That Number (AD-hoc)
原文地址:http://blog.csdn.net/wdkirchhoff/article/details/41286043