11-散列4 Hashing - Hard Version
分数 30 作者 何钦铭 单位 浙江大学
Question:
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
Answer:
# include<stdio.h>
# define MAXNUM 65535
// 数组中的元素结构
struct Node{
int Data; // 自身数据
int Offest; // 离开正确位置的偏移量,将会实时更新
int OffestCy; // 离正确位置的偏移量,固定不变
};
// 返回输出的位置下标
int PrintArray(struct Node Array[], int N);
int main(){
// 表长
int N;
scanf("%d",&N);
// 接收数据
int i;
struct Node Array[N];
for(i=0;i<N;i++){
struct Node New;
scanf("%d",&New.Data);
Array[i] = New;
}
// 计算非空单元的偏移量
int RightPos, Offest;
for(i=0;i<N;i++){
if(Array[i].Data==-1){
// 空单元偏移量记作-1
Array[i].Offest = -1;
continue;
}
RightPos = Array[i].Data % N;
Offest = i-RightPos;
// 保证偏移量都为正数
if(Offest<0)Offest+=N;
Array[i].Offest = Offest;
Array[i].OffestCy = Offest;
}
// 为了格式化输出,因此先单独输出一次
int index;
index = PrintArray(Array,N);
if(index!=-1)printf("%d",Array[index].Data);
// 循环输出直到index=-1
while( (index=PrintArray(Array,N)) != -1){
printf(" %d",Array[index].Data);
}
return 0;
}
// 返回每次输出的数的下标,没有要输出的数则下标返回-1
int PrintArray(struct Node Array[], int N){
int Min = MAXNUM;
int index = -1;
// 找出实时偏移量为0中最小的一个数字下标
int i;
for(i=0;i<N;i++){
if(Array[i].Offest == 0){
if(Array[i].Data<Min){
Min = Array[i].Data;
index = i;
}
}
}
// index==-1代表元素已经全部输出完毕
if(index==-1)return index;
// 将此数的偏移量更新为-1,代表后续马上被输出
Array[index].Offest = -1;
// 更新被影响到的元素的偏移量,分成两部分:一部分是下标比index大的数,一部分是下标比index小的数
for(i=index+1;i<N;i++){
if(i-index<=Array[i].OffestCy && Array[i].Offest>0)Array[i].Offest--;
}
for(i=0;i<index;i++){
if(i+1+N-1-index <= Array[i].OffestCy && Array[i].Offest>0)Array[i].Offest--;
}
// 返回结果
return index;
}