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