poj 2503 Babelfish(字典树或map或哈希或排序二分)

输入若干组对应关系,然后输入应该单词,输出对应的单词,如果没有对应的输出eh

此题的做法非常多,很多人用了字典树,还有有用hash的,也有用了排序加二分的(感觉这种方法时间效率最差了),这里我参考了MSDN中stl,使用了map,map是基于红黑树的,查询和插入的时间复杂度都是log(n),如果你构造了一个好的哈希函数的或也可以把时间复制度降到很低。字典树应该是最快的方法了,不过结构相对来说比较复杂,代码不大容易编写(对我而言)。

以下只给出我写的使用map的代码

#include <stdio.h>
#include <map>
#include <algorithm>
#include <string>

using namespace std;

map<string, string> m;
string s1, s2;
int main()
{
    char str1[50], str2[50], str[100];
    while(gets(str) && str[0] != '')
    {
        sscanf(str, "%s %s", str1, str2);
        s1.assign(str1);
        s2.assign(str2);
        m[s2] = s1;
    }
    while (scanf("%s", str) != EOF)
    {
        s1.assign(str);
        map<string, string>::iterator it = m.find(s1);
        if (it == m.end())
            puts("eh");
        else
            puts((*it).second.c_str());
    }
}


原文地址:https://www.cnblogs.com/xindoo/p/3595019.html