跳到正文

题解

哈希算法(p4305)题解

redbean0108约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年11月28日
收录
2026年2月2日
更新
2026年10月24日
篇幅
约 2 分钟
题目
P4305

版本

  1. v2当前
  2. v1

小豆发题解啦(^▽^)

C++
#include<bits/stdc++.h>
using namespace std;
const int maxn=50005;
const int M=100003;
int n;
int head[M];//链表个数
int cnt; //多少元素被存进去
struct node{
	int val,nxt;//val存储的是idx对应的key的值,nxt记录的是以对应的idx为值的链表系统
}e[maxn];
int get_hash(int key){//计算哈希函数值
	return (key%M+M)%M;
}
void add(int idx,int key){//将新数据插入在老的链表最前方
	e[cnt].val=key;
	e[cnt].nxt=head[idx];
	head[idx]=cnt++;
}
int insert(int key){
	int idx=get_hash(key);
	for(int i=head[idx];~i;i=e[i].nxt){//遍历以idx为hash值的链表
		if(e[i].val==key){
			return 0;
		}
	}
	add(idx,key);
	return 1;
}
void init(){
	cnt=0;
	memset(head,-1,sizeof(head));
}
int main(){
	int t;
	cin>>t;
	while(t--){
		cin>>n;
		init();
		for(int i=1;i<=n;i++){
			int key;
			scanf("%d",&key);//scanf的格式
			if(insert(key)){
				cout<<key<<" ";
			}
		}
		cout<<endl;
	}
	return 0;
}

小豆可是抄老师的代码抄了两年半o(╥﹏╥)o求关注!!!

原文