HDU1880 簡單字符串哈希

給定多個魔咒以及對應的效果,要求對於後面的魔咒或效果,及時給出對應的效果或魔咒。

建立兩張哈希表直接哈希就可以了。輸入需要稍微處理一下。哈希函數計算出來的值要保證是正的,否則讀數組會出錯。

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

const int N = 100010;
const int H = 100007;

struct Node
{
	char que[25];
	char ans[85];
	int next;
};

Node nodeA[N], nodeB[N];
int curA, curB;
int hashTableA[N], hashTableB[N];

void initHash()
{
	for (int i = 0; i < H; ++i) 
	{
		hashTableA[i] = -1;
		hashTableB[i] = -1;
	}
	curA = 0;
	curB = 0;
}

unsigned int getHash(char* str)
{
	unsigned int seed = 131;
	unsigned int hash = 0;
	while (*str)
	{
		hash = hash * seed + *str++;
	}
	return (hash & 0x7fffffff) % H;
}

void insertHash(char* que, char* ans)
{
	unsigned int h;
	h = getHash(que);
	strcpy(nodeA[curA].que, que);
	strcpy(nodeA[curA].ans, ans);
	nodeA[curA].next = hashTableA[h];
	hashTableA[h] = curA;
	++curA;
	h = getHash(ans);
	strcpy(nodeB[curB].que, que);
	strcpy(nodeB[curB].ans, ans);
	nodeB[curB].next = hashTableB[h];
	hashTableB[h] = curB;
	++curB;
}

int searchHashA(char* que)
{
	unsigned int h = getHash(que);
	int next = hashTableA[h];
	while (next != -1)
	{
		if (strcmp(que, nodeA[next].que) == 0) return next;
		next = nodeA[next].next;
	}
	return -1;
}

int searchHashB(char* ans)
{
	unsigned int h = getHash(ans);
	int next = hashTableB[h];
	while (next != -1)
	{
		if (strcmp(ans, nodeA[next].ans) == 0) return next;
		next = nodeB[next].next;
	}
	return -1;
}

int main()
{
	char str[120], que[25], ans[85], qlen, alen;
	int n, res;
	initHash();
	while (gets(str))
	{
		if (str[0] == '@') break;
		qlen = 0;
		for (int i = 1; str[i] != ']'; ++i)
		{
			que[qlen++] = str[i];
		}
		que[qlen] = 0;
		alen = 0;
		for (int i = qlen + 3; str[i] != 0; ++i)
		{
			ans[alen++] = str[i];
		}
		ans[alen] = 0;
		insertHash(que, ans);
	}
	scanf("%d", &n);
	getchar();
	while (n--)
	{
		gets(str);
		if (str[0] == '[')
		{
			qlen = strlen(str);
			str[qlen - 1] = 0;
			res = searchHashA(str + 1);
			if (res == -1) printf("what?\n");
			else printf("%s\n", nodeA[res].ans);
		}
		else
		{
			alen = strlen(str);
			res = searchHashB(str);
			if (res == -1) printf("what?\n");
			else printf("%s\n", nodeB[res].que);
		}
	}
	system("pause");
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章