2804:词典
Time Limit:
3000ms
Memory Limit:
65536kB
Description
你旅游到了一个国外的城市。那里的人们说的外国语言你不能理解。不过幸运的是,你有一本词典可以帮助你。
Input
首先输入一个词典,词典中包含不超过100000个词条,每个词条占据一行。每一个词条包括一个英文单词和一个外语单词,两个单词之间用一个空格隔开。而且在词典中不会有某个外语单词出现超过两次。词典之后是一个空行,然后给出一个由外语单词组成的文档,文档不超过100000行,而且每行只包括一个外语单词。输入中出现单词只包括小写字母,而且长度不会超过10。
Output
在输出中,你需要把输入文档翻译成英文,每行输出一个英文单词。如果某个外语单词不在词典中,就把这个单词翻译成“eh”。
Sample Input
dog ogday cat atcay pig igpay froot ootfray loops oopslay atcay ittenkay oopslay
Sample Output
cat eh loops
Hint
输入比较大,推荐使用C语言的I / O函数。
-----------------------------------------------------------------------------------------
首先简单采用查找的方法 但是在处理输入的时候遇到问题
由于题中要先输入字典中的内容(n行) 再一个空格 接着才是需要翻译的内容
查看了网上的代码 使用gets()函数比较方便 一个空行的话 gets后得到的字符串为“\0”
其次考虑到对字典进行排序,但是由于字典有原词和解释两个字符串,看到网上有人说可以使用map
使用#include<map>和map<string,string>可以使得原词和解释两个字符串关联起来
但其实使用普通的结构体 再使用排序+二分即可了
------------------------------------------------------------------------
给出百度的qsort()和bsearch()资料
typedef struct str
{
char str1[11];
char str2[11];
}str,*stri;
str strin[100001]=;
int compare(const void *a,const void *b)
{
return strcmp( ((str*)a)->str2 , ((str*)b)->str2 );
}
qsort(strin,total,sizeof(str),compare);
void *bsearch(const void *key, const void *base, size_t nelem, size_t width, int(*fcmp)(const void *, const *));
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
class dic{
public:
char engl[12];
char fore[12];
};
int cmp(const void *a,const void *b){
return strcmp(((dic *)a)->fore,((dic *)b)->fore);
}
int search(const void *a,const void *b){
return strcmp((char *)a,((dic *)b)->fore);
}
int main(){
dic words[100002];
char word[12],ch,tmp[25];
int count=0,i,j;
dic *p;
//读字典
gets(tmp);
while(tmp[0]!='\0'){
for(i=0;tmp[i]!=' ';i++)
words[count].engl[i]=tmp[i];
words[count].engl[i]='\0';
for(j=0,i++;tmp[i]!='\0';i++,j++)
words[count].fore[j]=tmp[i];
words[count].fore[j]='\0';
count++;
gets(tmp);
}
//getchar();
qsort(words,count,sizeof(words[0]),cmp);
//读文档
while(cin>>word&&word){
p=NULL;
p=(dic *)(bsearch(word,words,count,sizeof(words[0]),search));
if(p)
cout<<p->engl<<endl;
else
cout<<"eh"<<endl;
}
return 0;
}
-------------------------------------------------------------------------------------------
通过本题学习到:
1.c语言中的一些输入处理,输入字符串时如输入空格、空行怎么判断。如果用c语言,判断是否输入结束要用while(scanf("%s",word)!=EOF)
2.如果有关联的两个数组需要排序,可以使用map数据结构,还有用一个结构体(或类)将两个数组中的数据表示出来,再用qsort即可
3.qsort()+bsearch()是常用的组合,用于查找