Language of FatMouse
Time Limit:
10 Seconds Memory Limit:32768 KB
We all know that FatMouse doesn't speak English. But now he has to be prepared since our nation will join WTO soon. Thanks to Turing we have computers to help him.
Input Specification
Input consists of up to 100,005 dictionary entries, followed by a blank line, followed by a message of up to 100,005 words. Each dictionary entry is a line containing an English word, followed by a space and a FatMouse word.
No FatMouse word appears more than once in the dictionary. The message is a sequence of words in the language of FatMouse, one word on each line. Each word in the input is a sequence of at most 10 lowercase letters.
Output Specification
Output is the message translated to English, one word per line. FatMouse words not in the dictionary should be translated as "eh".
Sample Input
dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay atcay
ittenkay
oopslay
Output for Sample Input
cat
eh
loops
对我来说不习惯写gets(line),一般都是getchar然后链接,此题不好处理啊。然后只有屈服了。注意的是getsline+assign的耗时很严重,能不用就不要用。
算法应该是裸的字典树,懒人就用stl_map也吼了。
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<map>
using namespace std;
string s,a,b;
char line[41];
map<string,string>Map;
int main()
{
while(true){
int pos;
gets(line);
s.assign(line);
if(s.empty())break;
pos=s.find(' ');
a=s.substr(0,pos);
b=s.substr(pos+1);
Map[b]=a;
}
while(cin>>s)
{
if(Map.find(s)==Map.end()) printf("eh\n");
else cout<<Map[s]<<endl;;
}
return 0;
}
然后舶来一份字典树:http://www.cnblogs.com/DreamUp/archive/2010/07/23/1783410.html
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 100006
typedef struct node{
char s[12];
int h;
struct node *next[26];
}*Tree,T;
void init(Tree &root)
{
root=(Tree)malloc(sizeof(T));
root->h=0;
for(int i=0;i<26;i++)
root->next[i]=NULL;
} void insert(char path[],char s[],Tree root)
{
int len,i,j;
len=strlen(path);
for(i=0;i<len;i++)
{
if(root->next[path[i]-'a']==NULL)
{
Tree t=(Tree)malloc(sizeof(T));
for(j=0;j<26;j++)
{
t->next[j]=NULL;
t->h=0;
}
root->next[path[i]-'a']=t;
}
root=root->next[path[i]-'a'];
}
root->h=1;
strcpy(root->s,s);
} void find(char s[],Tree root)
{
int len,i;
len=strlen(s);
for(i=0;i<len;i++)
{
if(root->next[s[i]-'a']!=NULL)
root=root->next[s[i]-'a'];
else
break;
}
if(i==len && root->h==1)
puts(root->s);
else
puts("eh");
} int main()
{
Tree root;
int len,i;
char str[25],a[12],b[12];
init(root);
while(1)
{
gets(str);
len=strlen(str);
if(len==0)
break;
for(i=0;str[i]!=' ';i++);
strncpy(a,str,i);
a[i]=0;
strncpy(b,str+i+1,len-i-1);
b[len-i-1]=0;
insert(b,a,root);
}
while(scanf("%s",str)!=EOF)
find(str,root);
return 0;
}