题目
1806:词典
 总时间限制: 3000ms 内存限制: 65536kB
 描述
 你旅游到了一个国外的城市。那里的人们说的外国语言你不能理解。不过幸运的是,你有一本词典可以帮助你。
输入
 首先输入一个词典,词典中包含不超过100000个词条,每个词条占据一行。每一个词条包括一个英文单词和一个外语单词,两个单词之间用一个空格隔开。而且在词典中不会有某个外语单词出现超过两次。词典之后是一个空行,然后给出一个由外语单词组成的文档,文档不超过100000行,而且每行只包括一个外语单词。输入中出现单词只包括小写字母,而且长度不会超过10。
 输出
 在输出中,你需要把输入文档翻译成英文,每行输出一个英文单词。如果某个外语单词不在词典中,就把这个单词翻译成“eh”。
 样例输入
 dog ogday
 cat atcay
 pig igpay
 froot ootfray
 loops oopslay
atcay
 ittenkay
 oopslay
 样例输出
 cat
 eh
 loops
分析
不超过100000个词条
 文档不超过100000行,每次逐个比对,时间复杂度100000100000超时。
 词条建立后排序,每次二分查找,时间复杂度100000log100000还可以。
 用基于平衡二叉树建立的映射词典容器轻松搞定。
二分查找代码
#include <bits/stdc++.h>
 using namespace std;
 struct str{
 string s1,s2;//s1外语,
 }s[100010];
 int m;
 string sx;
 void view(string sx){
 cout<<sx<<endl;
 for(int i=0;i<m;i++)
 cout<<s[i].s1<<“\t”<<s[i].s2<<endl;
 cout<<endl;
 }
 bool cmp(str s1,str s2){
 return s1.s1<=s2.s1;
 }
 int main(){
 //freopen(“data.cpp”,“r”,stdin);
 while(1){
 getline(cin,sx);
 if(sx.empty())break;
 else{
 s[m].s2=sx.substr(0,sx.find(" “));
 s[m].s1=sx.substr(sx.find(” “)+1,sx.length());
 m++; 
 }
 }
 //view(“排序前”);
 sort(s,s+m,cmp);//排序
 //view(“排序后”);
 while(cin>>sx&&!sx.empty()){
 //cout<<sx<<”\t";
 int l=0,r=m-1,mid;//二分查找
 while(l<r){//左右没重叠就继续
 mid=(l+r)/2;
 if(sx<=s[mid].s1)r=mid;//目标值小于等于中间值,在左侧找
 else l=mid+1;//否则在右侧找
 }
 //cout<<l<<“\t”<<r<<endl;
 //cout<<“左:”<<s[l].s1<<“,”<<s[l].s2<<“\t右:”<<s[r].s1<<“,”<<s[r].s2<<endl; 
 if(s[r].s1==sx)cout<<s[r].s2<<endl;
 else cout<<“eh\n”;
 }
 return 0;
 }
映射词典容器map代码
#include <bits/stdc++.h>
 using namespace std;
 string sx;
 map<string,string> dic;//基于红黑树建立的映射词典容器
 void view(){
 cout<<sx<<endl;
 for(map<string,string>::iterator it=dic.begin();it!=dic.end();it++)//用迭代器便利词典
 cout<first<<“\t”<second<<endl;
 cout<<endl;
 }
 int main(){
 freopen(“data.cpp”,“r”,stdin);
 while(1){
 getline(cin,sx);
 if(sx.empty())break;
 else{
 string s2,s1;
 s2=sx.substr(0,sx.find(" “));
 s1=sx.substr(sx.find(” “)+1,sx.length());
 dic[s1]=s2;//往词典有序插入元素
 }
 }
 view();
 while(cin>>sx&&!sx.empty()){
 //cout<<sx<<”\t";
 if(dic.find(sx)!=dic.end())cout<<dic[sx]<<endl;//能找到该元素就输出对应映射元素
 else cout<<“eh\n”;
 }
 return 0;
 }