POJ-2503 Babelfish---map或者hash

题目链接:

https://vjudge.net/problem/POJ-2503

题目大意:

就像查找一本字典,根据输入的条目和要查询的单词,给出查询结果(每个单词长度不超过10)

解题思路:

map容器可以直接过,不过为了练习hash,写了个hash也可以过

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<string>
 5 #include<map>
 6 #include<set>
 7 #include<cmath>
 8 #include<algorithm>
 9 #include<vector>
10 #include<sstream>
11 #define lowbot(i) (i&(-i))
12 //#define Rotate(a, b) node(a.x + a.y - b.y, a.y + b.x - a.x)
13 using namespace std;
14 typedef long long ll;
15 const int maxn = 1000 + 10;
16 
17 const int mod = 99973;//一般为靠近总数的素数
18 struct Hashtable
19 {
20     string s, t;//hash存的值
21     Hashtable * next;
22     Hashtable()
23     {
24         next = 0;
25     }
26 };
27 Hashtable * Hash[mod];
28 void Hash_Insert(string s, string t)//s对应t
29 {
30     int key = 0;
31     for(int i = 0; i < s.size(); i++)
32         key = (key * 26 + (s[i] - 'a')) % mod;
33     if(!Hash[key])//该key第一个元素
34     {
35         Hashtable * p = new Hashtable;
36         p->s = s;
37         p->t = t;
38         Hash[key] = p;
39     }
40     else
41     {
42         Hashtable *p = Hash[key];
43         while(p->next)p=p->next;
44         Hashtable* temp = new Hashtable;
45         temp->s = s;
46         temp->t = t;
47         p->next = temp;
48     }
49 }
50 void Find(string s)
51 {
52     int key = 0;
53     for(int i = 0; i < s.size(); i++)
54         key = (key * 26 + (s[i] - 'a')) % mod;
55     if(Hash[key])
56     {
57         Hashtable * temp = Hash[key];
58         while(temp)
59         {
60             if(temp->s == s)
61             {
62                 cout<<temp->t<<endl;
63                 return;
64             }
65             temp = temp->next;
66         }
67     }
68     cout<<"eh"<<endl;
69     return;
70 }
71 
72 int main()
73 {
74     string s, s1, s2;
75     while(getline(cin, s))
76     {
77         if(s.size() == 0)break;
78         stringstream ss(s);
79         ss >> s1 >> s2;
80         Hash_Insert(s2, s1);
81     }
82     while(cin >> s2)
83     {
84         Find(s2);
85     }
86     return 0;
87 }
原文地址:https://www.cnblogs.com/fzl194/p/8949783.html