1. 程式人生 > >百練OJ:2804詞典

百練OJ:2804詞典

temp [0 stdin 做的 std int 原來 比較 max

題目是這樣的:

2804:詞典

總時間限制:
3000ms
內存限制:
65536kB
描述

你旅遊到了一個國外的城市。那裏的人們說的外國語言你不能理解。不過幸運的是,你有一本詞典可以幫助你。

輸入
首先輸入一個詞典,詞典中包含不超過100000個詞條,每個詞條占據一行。每一個詞條包括一個英文單詞和一個外語單詞,兩個單詞之間用一個空格隔開。而且在詞典中不會有某個外語單詞出現超過兩次。詞典之後是一個空行,然後給出一個由外語單詞組成的文檔,文檔不超過100000行,而且每行只包括一個外語單詞。輸入中出現單詞只包括小寫字母,而且長度不會超過10。
輸出
在輸出中,你需要把輸入文檔翻譯成英文,每行輸出一個英文單詞。如果某個外語單詞不在詞典中,就把這個單詞翻譯成“eh”。
樣例輸入
dog ogday
cat atcay
pig igpay
froot ootfray
loops oopslay

atcay
ittenkay
oopslay
樣例輸出
cat
eh
loops
提示
輸入比較大,推薦使用C語言的I / O函數。
輸入文檔時還好說,輸入詞典時就為了如何能在輸出一個空行之後退出折磨了好長時間。。。剛開始用scanf輸入,忘了字符串中間是有空格的,導致又是只接收了前半段,調試時才發現。。。換成gets吧,他後面又接不了getchar,因為那樣的話回回得輸入一個字符判斷一下。。。鬧了半天不知道怎麽整,上網查一下別人的吧,發現主要矛盾並不是這裏。。。人家都是用排序+二分做的,還都用到了一個奇怪的函數sscanf(),有點不解,我這麽做不也行嗎(線性查找),於是使用學到的判斷遇到回車符退出的辦法:在gets後面用if(!strcmp(temp,"")) break;這個,就很方便了!原來scanf會把回車符放在輸入緩沖區裏,需要用getchar吸收,而gets只會讀取一行的數據,忽略掉換行符。結果終於本地過了,一提交,超時。。。我才意識到時間復雜度出了問題,那麽龐大的數據,是不應該用線性查找的,轉而二分查找,那就先得排序,然後才發現,我用strstr()找字符串的方法,根本不適合二分。。。跟誰去比啊。。於是,半拉可嘰的代碼終於寫不下去了,,換算法,用個結構體定義吧。。.........

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
char dic[100000][22];
char txt[100000][22];
bool cmp(char *x,char *y)
{
return strcmp(x,y)<0;
}
int main()
{
int cnt;
long i=0,j=0;
// char c;
while(gets(dic[i])){
if(strcmp(dic[i++],"")==0) break;
}
sort(dic,dic+i,cmp);
while(gets(txt[j])&&j<=100000){
//getchar();
int beg=0,end=i;
while(beg<=end){
int mid=(beg+end)/2;
if()
}
for(cnt=0;cnt<i;cnt++){
if(strstr(dic[cnt],txt[j])!=NULL){
*(strstr(dic[cnt],txt[j])-1)=‘\0‘;
break;
}
}
if(cnt>=i)
printf("eh\n");
else
printf("%s\n",dic[cnt]);
j++;
}
return 0;
}

以上是我的半拉可嘰的代碼,下面是AC的網友代碼:

#include <stdio.h> #include <string.h> #include <algorithm> #define MAX_WORD_LEN 11 #define MAX_DICTION_ITEM (100000 + 10) using std::sort; struct Dictionary { char szWord[MAX_WORD_LEN]; char szEnglish[MAX_WORD_LEN]; }; Dictionary diction[MAX_DICTION_ITEM]; bool CmpDictionItem(Dictionary one, Dictionary two) { return strcmp(one.szWord, two.szWord) < 0; } int FindEnglish(char* pszWord, int nItemNum) { int nBeg = 0, nEnd = nItemNum - 1; int nCmp = 0; while (nBeg <= nEnd) { int nMid = (nBeg + nEnd) / 2; nCmp = strcmp(pszWord, diction[nMid].szWord); if (nCmp == 0) { return nMid; } else if (nCmp < 0) { nEnd = nMid - 1; } else { nBeg = nMid + 1; } } return -1; } int main() { char szStr[30]; char szWord[MAX_WORD_LEN]; int nCount = 0; int nAnsItem = 0; while (fgets(szStr, 29, stdin), szStr[0] != ‘\n‘) { sscanf(szStr, "%s%s", diction[nCount].szEnglish, diction[nCount].szWord); ++nCount; } sort(diction, diction + nCount, CmpDictionItem); while (scanf("%s", szWord) == 1) { if ((nAnsItem = FindEnglish(szWord, nCount)) != -1) { printf("%s\n", diction[nAnsItem].szEnglish); } else { printf("eh\n"); } } return 0; } 學習了。

百練OJ:2804詞典