Fafu 1266 数数(hash应用)

本文介绍了一个使用哈希表解决特定问题的实例。通过将2^31范围内的整数进行模运算,得到对应的哈希值,并将其存入哈希链表中。此程序能够高效地查找并统计特定数值出现的次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://acm.fafu.edu.cn/problem.php?id=1266


把2^31范围内的数 %10000求得真hash值

把值存到hash链表中


#include <stdio.h>
#include <string.h>

struct node{
	int val;
	node * next;
}hash[10000];


int main()
{
	freopen("E:\\input.txt", "r", stdin);
	int n;
	while(scanf("%d", &n) != EOF)
	{
		memset(hash, 0, sizeof(hash));
		int hashVal;
		while(n--)
		{
			int v;
			scanf("%d", &v);
			hashVal = v%10000;

			node * last = hash[hashVal].next; //save
			hash[hashVal].next = new node;
			hash[hashVal].next->val = v;
			hash[hashVal].next->next = last;
		}

		int m;
		scanf("%d", &m);
		while(m--)
		{
			int query;
			scanf("%d", &query);
			hashVal = query % 10000;
			node * pointer = hash[hashVal].next;

			int times = 0;
			while(pointer != NULL)
			{
				if(pointer->val == query)
					times++;

				pointer = pointer->next;
			}

			if(m != 0)
				printf("%d ", times);
			else
				printf("%d\n", times);
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值