HDU1880 简单字符串哈希

本文介绍了一个简单的魔法咒语查询系统的实现方法。通过构建两个哈希表来快速匹配咒语及其效果,支持用户查询咒语的效果或根据效果查找咒语。文章提供了完整的C++代码实现,展示了如何进行哈希表的初始化、插入和搜索操作。

给定多个魔咒以及对应的效果,要求对于后面的魔咒或效果,及时给出对应的效果或魔咒。

建立两张哈希表直接哈希就可以了。输入需要稍微处理一下。哈希函数计算出来的值要保证是正的,否则读数组会出错。

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值