Problem C: Babelfish
You have just moved from Waterloo to a big city. The people here speak an incomprehensible dialect of a foreign language. Fortunately, you have a dictionary to help you understand them.Input consists of up to 100,000 dictionary entries, followed by a blank line, followed by a message of up to 100,000 words. Each dictionary entry is a line containing an English word, followed by a space and a foreign language word. No foreign word appears more than once in the dictionary. The message is a sequence of words in the foreign language, one word on each line. Each word in the input is a sequence of at most 10 lowercase letters. Output is the message translated to English, one word per line. Foreign 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
这道题题意非常简单,给出一个字典,找出对应单词的翻译。这种类型直接用map非常简单,可是我非常手贱的写了一个二分查找,其中还出现一些小错误。
#include<iostream> #include<algorithm> #include<string> #include<cstdio> using namespace std; int k; class trans { public: string st1,st2; }word[100005]; bool cmp(trans x,trans y) { return x.st2<y.st2; } int search(string str) { int left=0,right=k-1,mid; while(left<=right) { mid=(left+right)/2; if(word[mid].st2<str) { left=mid+1; } else if(word[mid].st2>str) { right=mid-1; } else return mid; } return -1; } int main() { string str; k=0; while(cin>>str) { char ch; ch=getchar(); if(ch!=‘ ‘) { sort(word,word+k,cmp); int r=search(str); if(r!=-1) { cout<<word[r].st1<<endl; } else { cout<<"eh"<<endl; } break; } word[k].st1=str; cin>>str; word[k].st2=str; k++; } while(cin>>str) { int cnt=search(str); if(cnt!=-1) { cout<<word[cnt].st1<<endl; } else { cout<<"eh"<<endl; } } return 0; }