Hash Function (并查集) 牛客

探讨了在已知哈希函数和冲突解决策略的情况下,如何从给定的哈希表重建最小字典序的元素插入序列。通过使用小根堆和并查集的数据结构,算法能够有效地找到并排序可能的插入顺序。

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

Chiaki has just learned hash in today’s lesson. A hash function is any function that can be used to map data of arbitrary size to data of fixed size. As a beginner, Chiaki simply chooses a hash table of size n with hash function h(x) = x \bmod nh(x)=xmodn.
Unfortunately, the hash function may map two distinct values to the same hash value. For example, when n = 9 we have h(7) = h(16) = 7. It will cause a failure in the procession of insertion. In this case, Chiaki will check whether the next position (h(x) + 1) \bmod n(h(x)+1)modn is available or not. This task will not be finished until an available position is found. If we insert {7, 8, 16} into a hash table of size 9, we will finally get {16, -1, -1, -1, -1, -1, -1, 7, 8}. Available positions are marked as -1.
After done all the exercises, Chiaki became curious to the inverse problem. Can we rebuild the insertion sequence from a hash table? If there are multiple available insertion sequences, Chiaki would like to find the smallest one under lexicographical order.
Sequence a1, a2, …, an is lexicographically smaller than sequence b1, b2, …, bn if and only if there exists i (1 ≤ i ≤ n) satisfy that ai < bi and aj = bj for all 1 ≤ j < i.
题意: 已知哈希函数为 hash(x) = x mod n ,且如果出现哈希冲突,则 hash(x) = hash(x+1)。
现给出一张 hash 表,长度为 n,问字典序最小插入顺序。
思路: 先将a[ i ] mod n==i放进小根堆里,每次优先弹出最小,利用并查集维护前驱后继

#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5;
int a[N];
int fa[N];
bool vis[N];
int cnt,num;
struct node
{
	int val,pos;
	node(int x,int y)
	{
		val=x,pos=y;
	}
	bool friend operator < (node a,node b)
	{
		return a.val>b.val;
	}
};

int fid(int x)
{
	return fa[x]==x?x:fa[x]=fid(fa[x]);
}
int main()
{
	priority_queue<node>q;
	int T,n;
	scanf("%d",&T);
	while(T--)
	{
		num=0;
		memset(vis,0,sizeof vis);
		vector<int>ans;
		scanf("%d",&n);
		for(int i=0;i<n;i++)
		{
			fa[i]=i;
			scanf("%d",&a[i]);
			if(a[i]==-1)
				continue;
			if(a[i]%n==i)
			{
				q.push(node(a[i],i));
				vis[i]=1;
			}
			num++;
		}
		while(!q.empty())
		{
			node x=q.top();
			q.pop();
			ans.push_back(x.val);
			int to=fa[fid(x.pos)]=fid((x.pos+1)%n);
			if(vis[to]||a[to]==-1||fid(a[to]%n)!=to)
				continue;
			q.push(node(a[to],to));
			vis[to]=1;
		}
		if(ans.size()<num)
		{
			printf("-1\n");
		}
		else
		{
			for(auto it : ans)
			{
				printf("%d ",it);
			}
			puts("");
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值