Description:
输入一组<key: string s1, value: string s2> 的二元组, 之后给出一系列的查询,每个查询是一个string作为value, 要求输出对应的key.
input:
若干<string, string>二元组,每行一个
空行
若干查询, 每个一行
output:
若干查询结果,每个一行。
Analysis:
这一题是裸的串的hash,关键在于hash函数,由于字符串的每个字符的ASCII码之间的数字相差不大。所以常用的一些数的hash函数效果就不好了。看到的一些串的hash主要是用移位加异或。代码给出DJBhash(首先是在discuss上看到的)
代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<stack>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<sstream>
#include<cmath>
#include<iterator>
#include<bitset>
#include<stdio.h>
using namespace std;
#define _for(i,a,b) for(int i=(a);i<(b);++i)
#define _rep(i,a,b) for(int i=(a);i<=(b);++i)
typedef long long LL;
const int INF = 1 << 30;
const int maxn = 100005;
struct Node {
char s1[12], s2[12];
int next;
}table[maxn];
const int HASHSIZE = 10007;
int head[HASHSIZE];
int Hash(char s[]) {
int len = strlen(s);
int h = 5381;
for (int i = 0; i<len; ++i) {
h = (h * 33 ^ s[i]) % HASHSIZE;
}
return abs(h);
}
int pos;
void find(char s[]) {
int h = Hash(s);
for (int now = head[h]; now; now = table[now].next) {
if (strcmp(s, table[now].s2) == 0) { printf("%s\n", table[now].s1); return; }
}
puts("eh");
}
int main()
{
//freopen("C:\\Users\\admin\\Desktop\\in.txt", "r", stdin);
//freopen("C:\\Users\\admin\\Desktop\\out.txt", "w", stdout);
char s1[12], s2[12];
pos = 1;
memset(head, 0, sizeof(head));
char buffer[24];
while (gets(buffer)) {
if (buffer[0] == '\0') break;
sscanf(buffer, "%s %s", table[pos].s1, table[pos].s2);
int h = Hash(table[pos].s2);
table[pos].next = head[h];
head[h] = pos++;
}
while (gets(buffer)) {
find(buffer);
}
return 0;
}