PTA 11-散列4 Hashing - Hard Version
Given a hash table of size N, we can define a hash function H(x)=x%N. Suppose that the linear probing is used to solve collisions, we can easily obtain the status of the hash table with a given sequence of input numbers.
However, now you are asked to solve the reversed problem: reconstruct the input sequence from the given status of the hash table. Whenever there are multiple choices, the smallest number is always taken.
Input Specification:
Each input file contains one test case. For each test case, the first line contains a positive integer N (≤1000), which is the size of the hash table. The next line contains N integers, separated by a space. A negative integer represents an empty cell in the hash table. It is guaranteed that all the non-negative integers are distinct in the table.
Output Specification:
For each test case, print a line that contains the input sequence, with the numbers separated by a space. Notice that there must be no extra space at the end of each line.
Sample Input:
11
33 1 13 12 34 38 27 22 32 -1 21
结尾无空行
Sample Output:
1 13 12 21 33 34 38 27 22 32
结尾无空行
思路
1.观察出(我是看陈越姥姥的视频)这是个拓扑排序

2.优先队列priority_queue相关知识
参考链接
定义:priority_queue<Type, Container, Functional>
Type 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),Functional 就是比较的方式,当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆
默认:
//升序队列
priority_queue <int,vector<int>,greater<int> > q;
//降序队列
priority_queue <int,vector<int>,less<int> >q;
重写函数cmp
struct cmp {
bool operator()(int i, int j) {
return Hash[i] > Hash[j];//降序
}
};
Code
#include<iostream>
#include<vector>
#include<queue>
#define MaxN 1001
using namespace std;
int Hash[MaxN];
struct cmp {
bool operator()(int i, int j) {
return Hash[i] > Hash[j];
}
};
int main(){
int N;
scanf("%d",&N);
vector<vector<int> > v(N);//记录每个对象的拓扑前的对象下标
vector<int> Indegree(N);//入度的数组下标
priority_queue<int,vector<int>,cmp> q;//用来输出一样的Indegree值,Hash值最小的数
for(int i=0;i<N;i++){
cin>>Hash[i];
}
for(int i=0;i<N;i++){
if(Hash[i]>=0){//非负->不为空
int key=Hash[i]%N;
Indegree[i]=(N+i-key)%N;//有多少个数要在这个数之前输出
if(Indegree[i]==0){//在该有的位置上
q.push(i);//入队
}else{
for(int j=0;j<Indegree[i];j++){
v[(key+j)%N].push_back(i);
}
}
}
}
int flag=1;
while(!q.empty()){
int t=q.top();
q.pop();
if(flag){
flag=0;
printf("%d",Hash[t]);
}else{
printf(" %d",Hash[t]);
}
for(int i=0;i<v[t].size();i++){
if(--Indegree[v[t][i]]==0){
q.push(v[t][i]);
}
}
}
printf("\n");
return 0;
}

本文介绍了一种从给定的哈希表状态还原输入序列的方法,利用线性探测解决冲突,并通过拓扑排序进行逆向操作。代码中使用了优先队列来按顺序输出具有相同入度的元素,确保输出的序列正确。
6203

被折叠的 条评论
为什么被折叠?



