11-散列4 Hashing - Hard Version (30 分) 散列表反向思維——用拓撲排序做

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

題意:n爲表長,輸出目前每個格子裏填的數字,負值即爲空,問輸入的序列是怎麼樣的

思路:其實這是一道拓撲排序的題,根據偏移量建立邊的關係

若結點a定位在2,但是他其實在3,說明發生了衝突,這是衝突他的結點必然在他之前輸入

 

順便重溫了一下優先隊列,因爲存的是下標,所以不能簡單的greater<int>,要用cmp哦

#include <stdio.h>
#include <string.h>
#include <string>
#include <map>
#include <vector>
#include <queue>
#include <math.h>
#include <algorithm>
#include <iostream>
#define INF 0x3f3f3f3f
using namespace std;
vector<int> v[10005];//單向圖 - 存的是下標,不是數值 
int a[10005];
int degree[10005];//入度
struct cmp 
{
    bool operator()(int i,int j) 
    {
        return a[i]>a[j];
    }
};
priority_queue<int,vector<int>,cmp > q;
int main()
{
	int n,i,j,x;
	memset(degree,0,sizeof degree);
	scanf("%d",&n);
	for(i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
		if(a[i]>=0)
		{
			x=a[i]%n;
			degree[i]=(i+n-x)%n;
			if(degree[i]!=0)//發生衝突 
			{
				for(j=0;j<=degree[i];j++)
				v[(x+j)%n].push_back(i);	
			}
			else
			q.push(i);
		}
	}
	//for(i=0;i<n;i++)
	//printf("%d : %d\n",a[i],degree[i]);
	int f=0;//控制空格輸出 
	while(!q.empty())
	{
		int u=q.top();	
		q.pop();
		
		if(f)printf(" ");
		printf("%d",a[u]);
		f++;
			
		for(i=0;i<v[u].size();i++)
		{
			degree[v[u][i]]--;
			if(degree[v[u][i]]==0)
			q.push(v[u][i]);
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章