UVa 10282 - Babelfish

题目链接:

UVA:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1223

poj: http://poj.org/problem?id=2503


类型: 哈希表


原题:

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名大笑

/*
 * 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;
}




—— 生命的意义,在于赋予它意义。

原创http://blog.csdn.net/shuangde800By D_Double (转载请标明)











你可能感兴趣的:(uva)