题意:输入key value对的字典,要求再次输入value要能给出key,如果不存在输出'eh'
使用哈希方法,对字符串使用ELFHash函数,这题最重要的是对输入数据的处理。
code:
<span style="font-size:18px;">#include <iostream>
using namespace std;
const int HASH_BASE = 100001;
int hashTable[HASH_BASE];
int cur;
char ans[11];
struct HashNode{
char s1[11];
char s2[11];
int next;
};
HashNode node[100005];
void initHash()
{
for (int i = 0; i < HASH_BASE; i++)
{
hashTable[i] = -1;
}
cur = 0;
}
int ELFhash(char *key){
unsigned long h = 0;
unsigned long x = 0;
while (*key)
{
h = (h << 4) + (*key++); //h左移4位,当前字符ASCII存入h的低四位
if ((x = h & 0xF0000000L) != 0)
{ //如果最高位不为0,则说明字符多余7个,如果不处理,再加第九个字符时,第一个字符会被移出
//因此要有如下处理
h ^= (x >> 24);
//清空28~31位
h &= ~x;
}
}
return h % HASH_BASE;
}
void insertHash(char s1[],char s2[])
{
int value = ELFhash(s2);
strcpy(node[cur].s1,s1);
strcpy(node[cur].s2,s2);
node[cur].next = hashTable[value];
hashTable[value] = cur;
cur++;
}
bool searchHash(char s[])
{
int value = ELFhash(s);
int next = hashTable[value];
while (next != -1)
{
if (strcmp(s, node[next].s2) == 0)
{
strcpy(ans,node[next].s1);
return true;
}
next = node[next].next;
}
return false;
}
int main()
{
char s1[11],s2[11],t;
initHash();
while (true)
{
char temp;
if ((temp = getchar()) == '\n')
break;
s1[0] = temp;
int i = 1;
while (true)
{
temp = getchar();
if (temp == ' ')
{
s1[i] = '\0';
break;
}
else
s1[i++] = temp;
}
cin >> s2;
getchar();
insertHash(s1,s2);
}
char word[11];
while (cin >> word)
{
memset(ans,'\0',sizeof(ans));
if (searchHash(word))
cout << ans << endl;
else
cout << "eh" << endl;
}
//system("pause");
return 0;
}
</span>