UVA 10282 - Babelfish

链结:戳我

RTE...我也不知道为什么。

这是一道典型的Hash的题目,用STL的map可以做,但是那就失去了做这道题的意义了。可惜还是有小问题。懒得改了。

View Code
  1 #include <iostream>
  2 #include <cstring>
  3 using namespace std;
  4 
  5 const int MAXENTRY = 10001;
  6 const int MAXHASHSIZE = 1000000;
  7 const int MAXLENGTH = 11;
  8 const int MAXLINE = 100;
  9 typedef char Word[MAXLENGTH];
 10 
 11 Word dic[MAXENTRY], wd[MAXENTRY];
 12 int head[MAXHASHSIZE], next[MAXENTRY];
 13 
 14 void init_lookup_table() {
 15     memset(head, 0, sizeof(head));
 16     memset(next, 0, sizeof(next));
 17     memset(dic, 0, sizeof(dic));
 18     memset(wd, 0, sizeof(wd));
 19 }
 20 
 21 int hash(char w[]) {
 22     int result = 0, length = strlen(w);
 23     for (int i = 0; i < length; i++){
 24         result = (result<<2) + w[i] - 'a' + 1;
 25     }
 26     return result % MAXHASHSIZE;
 27 }
 28 
 29 void insert(int s) {
 30     int h = hash(dic[s]);
 31     int u = head[h];
 32     while (u){
 33         if (memcmp(dic[s], dic[u], sizeof(dic[s])) == 0)
 34             return;
 35         u = next[u];
 36     }
 37     next[s] = head[h];
 38     head[h] = s;
 39 }
 40 
 41 int find(char w[]) {
 42     int h = hash(w);
 43     int u = head[h];
 44     while (u){
 45         if (memcmp(dic[u], w, sizeof(w)) == 0){
 46             break;
 47         }
 48         u = next[u];
 49     }
 50     return u;
 51 }
 52 
 53 
 54 int main(int argc, char *argv[]){
 55 #ifndef ONLINE_JUDGE
 56     freopen("input.txt", "r", stdin);
 57 #endif
 58     char line[MAXLINE];
 59     int n_entry = 1;
 60     memset(line, 0, sizeof(line));
 61     init_lookup_table();
 62 
 63     while (cin.getline(line, MAXLINE) && strlen(line) != 0){
 64         int length = strlen(line), i_wd = 0, i_dic = 0;
 65         bool dictionary = false;
 66         for (int i = 0; i < length; i++){
 67             while (line[i] == ' ')
 68                 i++;
 69             if (!dictionary){
 70                 while (isalpha(line[i]))
 71                     wd[n_entry][i_wd++] = line[i++];
 72                 dictionary = true;
 73             }
 74             else{
 75                 while (isalpha(line[i]))
 76                     dic[n_entry][i_dic++] = line[i++];
 77             }
 78         }
 79         insert(n_entry);
 80         n_entry++;
 81     }
 82 
 83     Word word;
 84     while (cin.getline(line, MAXLINE) && strlen(line) != 0){
 85         memset(word, 0, sizeof(word));
 86         int length = strlen(line), i_word = 0;
 87         for (int i = 0; i < length; i++){
 88             while (line[i] == ' ')
 89                 i++;
 90             while (isalpha(line[i]))
 91                 word[i_word++] = line[i++];
 92         }
 93 
 94         int index = find(word);
 95         if (index)
 96             cout << wd[index] << endl;
 97         else
 98             cout << "eh" << endl;
 99     }
100     return 0;
101 }

 

posted @ 2013-02-18 23:54  frankdj  阅读(200)  评论(0编辑  收藏  举报