| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
字符串多项式法开放寻址hash#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
using namespace std;
const int MOD = 1000007;
const int M = 10 + 5;
const int PRIME = 37;
struct Entry { char key[M], value[M]; } ht[MOD];
int hash(const char *str)
{
int idx = 0;
for (int i = 0, len = strlen(str); i < len; i++) idx = idx * PRIME + str[i] - 'a';
return abs(idx) % MOD;
}
bool check(const char *str1, const char *str2)
{
int len1 = strlen(str1), len2 = strlen(str2);
if (len1 != len2) return false;
for (int i = 0; i < len1; i++) if (str1[i] != str2[i]) return false;
return true;
}
void insert(const char *key, const char *value)
{
int idx = hash(key);
while (ht[idx].key[0] != '\0') idx = (idx + 1) % MOD;
strcpy(ht[idx].key, key); strcpy(ht[idx].value, value);
}
void get(const char *key, char *value)
{
int idx = hash(key);
while (ht[idx].key[0] != '\0')
{
if ( check(key, ht[idx].key) ) { strcpy(value, ht[idx].value); return; }
idx = (idx + 1) % MOD;
}
strcpy(value, "eh");
}
int main()
{
char key[M], value[M], tmp[2 * M];
while (gets(tmp) && strlen(tmp))
{
int pos = 0, i;
for (i = 0; tmp[pos] != ' '; pos++, i++) value[i] = tmp[pos]; value[i] = '\0'; pos++;
for (i = 0; tmp[pos] != '\0'; pos++, i++) key[i] = tmp[pos]; key[i] = '\0';
insert(key, value);
}
while (gets(key)) get(key, value), printf("%s\n", value);
return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator