http://162.105.81.212/JudgeOnline/problem?id=2503
数据不大, 可以用STL的map水过.900MS
后来写了一个hash的, 效率高点200MS
//hash
#include<iostream> using namespace std; #define MAX 200000 struct Dic { char w[11], f[11]; }dic[MAX/2]; int hash[MAX]; int main() { int i, j, k=0, hashValue; char s[25]; memset(hash, -1, sizeof(hash)); while(gets(s) && s[0] != 0) { for(i=0; s[i]!=' '; i++) dic[k].w[i] += s[i]; dic[k].w[i] += 0; for(++i,j=0; s[i]!='/0'; i++,j++) dic[k].f[j] += s[i]; dic[k].f[j] += 0; i = hashValue = 0; while(dic[k].f[i]) { hashValue += hashValue*26 + dic[k].f[i++]; hashValue %= MAX; } while(hash[hashValue] != -1) hashValue = (hashValue+1)%MAX; hash[hashValue] = k; k++; } while(scanf("%s", s) != EOF) { i = hashValue = 0; while(s[i]) { hashValue += hashValue*26 + s[i++]; hashValue %= MAX; } while(strcmp(dic[hash[hashValue]].f, s) != 0 && hash[hashValue] != -1) hashValue = (hashValue+1)%MAX; if(hash[hashValue] == -1) puts("eh"); else printf("%s/n", dic[hash[hashValue]].w); } return 0; }
//map,
map用得不熟练,- -....
#include<iostream> #include<map> #include<string> using namespace std; int main() { int i; char s[25], c; map<string, string> map; string w, f, tmp; while(gets(s) && s[0] != 0) { w = f = ""; for(i=0; s[i]!=' '; i++) w += s[i]; for(++i; s[i]!='/0'; i++) f += s[i]; map[f] = w; } while(scanf("%s", s) != EOF) { tmp = map[string(s)]; if(tmp.size() == 0) puts("eh"); else printf("%s/n", tmp.c_str()); } return 0; }
本文通过两个实现方式——使用STL的map和自定义hash表来解决字符串映射问题,展示了如何高效地进行查找与匹配。利用C++语言特性,介绍了具体的代码实现细节,并比较了两种方法的时间效率。
852

被折叠的 条评论
为什么被折叠?



