题目:http://poj.org/problem?id=2503
AC代码(C++):
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <vector>
#include <queue>
#include <math.h>
#include <string>
#include <string.h>
#include <bitset>
#define INF 0xfffffff
#define MAXN 100005
using namespace std;
const int N = 100005;
const int H = 99997;
struct Node
{
char f[12];
char e[12];
int next;
};
Node node[N];
int cur;
int hashTable[H];
void initHash()
{
cur = 0;
for (int i = 0; i < H; ++i) hashTable[i] = -1;
}
int getHash(char* f){
int hash = 0;
for(int i = 0; f[i]!='\0'; i++)hash += (f[i] - 'a') * (int)pow(4.0,i+1) % H;
return hash%H;
}
void insertHash(char* f, char* e)
{
int h = getHash(f);
strcpy(node[cur].f,f);
strcpy(node[cur].e,e);
node[cur].next = hashTable[h];
hashTable[h] = cur;
cur++;
}
bool searchHash(char* f)
{
int h = getHash(f);
int next = hashTable[h];
while (next != -1)
{
if (strcmp(node[next].f,f)==0){
strcpy(f,node[next].e);
return true;
}
next = node[next].next;
}
return false;
}
int main(){
char f[12];
char e[12];
char tmp;
initHash();
while(1){
if((tmp = getchar())=='\n')break;
e[0] = tmp;
int cnt = 1;
while(1){
if((tmp = getchar())==' ')break;
e[cnt++] = tmp;
}
e[cnt] = '\0';
cin>>f;
getchar();
insertHash(f,e);
}
while(cin>>f){
if(searchHash(f))cout<<f<<endl;
else cout<<"eh\n";
}
}
总结: 简单的串哈希. 听说用map做的更快.