您的位置:首页 > 其它

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

2013-10-30 15:59 323 查看
输入若干组对应关系,然后输入应该单词,输出对应的单词,如果没有对应的输出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] != '\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());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: