poj 2804 詞典

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()是常用的組合,用於查找


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章