题意: 给出 (key ,demo)两个字符串, 求输入demo的时候, 要输出相应的key, 如果没有key, 就输出"eh";
题解: 简单的哈希处理, 链表处理冲突
code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn = 1e6+5;
char a[maxn][12], b[maxn][12];
bool vis[maxn];
struct node{
char *s;
char *w;
node *next;
}word[maxn];
int getHashKey(char *s){
int key=0;
while(*s != '\0'){
key = (key*131 + (*s)*151)%maxn;
s++;
}
return key%maxn;
}
void TurnToHash(char *s, char *p){
int key = getHashKey(s);
if(vis[key]){
node *q = new node;
q->s = s;
q->w = p;
q->next=word[key].next;
word[key].next = q;
} else {
word[key].s = s;
word[key].w = p;
word[key].next = NULL;
}
vis[key] = 1;
}
void query(char *c){
int key = getHashKey(c);
if(!vis[key]) {
printf("eh\n");
return ;
}
node *p = &word[key];
while(p){
if(!strcmp(p->s, c)) {
printf("%s\n", p->w);
return ;
}
p=p->next;
}
printf("eh\n");
return ;
}
int main(){
//freopen("in.txt","r",stdin);
memset(vis, 0, sizeof(vis));
int i=1;
while(true){
scanf("%s", a[i]);
if(getchar()=='\n') break;
scanf("%s", b[i]);
TurnToHash(b[i], a[i]);
i++;
}
query(a[i]);
char t[50];
while(~scanf("%s", t)){
if(t[0]=='\0') break;
query(t);
}
return 0;
}