程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> UVa 10282 - Babelfish

UVa 10282 - Babelfish

編輯:C++入門知識


原題:
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


題目大意:
你到了一個陌生的地方,這個地方的單詞和英語單詞不一樣。 每個英文單詞都對應這一個當地的單詞(都是一一對應,不會重復出現)。然後會給出一些當地的單詞, 要你輸出所對應的英文單詞。


分析與總結:
英文單詞和當地單詞就是簡單的映射關系。有於題目所給的數量達到100,000, 用hash建立映射或者直接排序後二分查找,就算是可以勉強通過,速度應該也很不理想。
所以這題的最佳方式是用哈希表來建立映射關系。
速度還不錯,  跑進了rank第2名
[cpp]
/*
 * Uva 10282 - Babelfish
 * 哈希表
 * Time: 0.076s (UVa)
 * Author: D_Double
 */ 
#include<iostream>   
#include<cstdio>   
#include<cstring>   
#define MAXN 100003 
using namespace std;   
typedef char Word[12]; 
 
 
Word english[MAXN], foreign[MAXN]; 
const int HashSize = 100003; 
int N, head[HashSize], next[HashSize]; 
 
inline void init_lookup_table(){ 
    N=1;   
    memset(head, 0, sizeof(head)); 

 
inline int hash(char *str){ // 字符串哈希函數 
    int seed = 131; 
    int hash=0; 
    while(*str) hash = hash * seed + (*str++); 
    return (hash & 0x7FFFFFFF) % HashSize; 

 
int add_hash(int s){ 
    int h = hash(foreign[s]); 
    int u = head[h]; 
    while(u) u = next[u]; 
    next[s] = head[h]; 
    head[h] = s; 
    return 1; 

 
int search(char *s){ 
    int h = hash(s); 
    int u = head[h]; 
    while(u){ 
        if(strcmp(foreign[u], s)==0) return u; 
        u = next[u]; 
    } 
    return -1; 

int main(){ 
    char str[25]; 
    N = 1; 
    init_lookup_table(); 
    while(gets(str)){ 
        if(str[0]=='\0') break; 
        int i;  
        for(i=0; str[i]!=' '; ++i) 
            english[N][i] = str[i]; 
        english[N][i] = '\0'; 
        char *p=str+i+1;  
        i=0;  
        while(*p) foreign[N][i++] = *p++; 
        foreign[N][i]='\0'; 
        add_hash(N); 
        ++N; 
    } 
    // 查詢 
    while(gets(str)){ 
        int index = search(str); 
        if(index==-1) puts("eh"); 
        else printf("%s\n", english[index]); 
    } 
    return 0; 


 

作者:shuangde800

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved