代码有问题 先存着
2017/7/25日更新
这道题的意思就是根据已有的一个哈希表,推断出每个数字的插入顺序,其中有多重选择时,小的总是最先输入
这道题刚开始根据陈越老师的思路和看了一下别人的代码写出来了,但结果一直不对。今天看了一下,是我pop优先队列中的top值时,位置放错了。总是根据DeleteEdge()
函数,刚把一个数的入度减为0压入优先队列,就被我弹出来了。改正后根据给出的例子结果正确,但没有去ac测试,就暂认为正确。希望如果看到我的这个代码并发现错误的同学告诉我一下,谢谢。
另外我这里把初次利用Hash()算的余数为0的数的入度置为-1,因为之后不会用到了,而其他的数字的入度减为0时,压入队列
Given a hash table of size N, we can define a hash function . 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
#include "StdAfx.h"
#include <vector>
#include <queue>
#include<iostream>
#include <functional>
using namespace std;
#define MAX 1000
struct HashNode
{ int seq;
int Key;
int indegree;
friend bool operator< (HashNode n1, HashNode n2) //表示由小到大排序 优先队列
{
return n1.Key > n2.Key;
}
}HashTable[MAX];
int TMatric[MAX][MAX];
priority_queue<HashNode> Q;
void calMatric(int n)//建立依赖关系矩阵
{
int i,haspos,currentpos,p;
for(i=0;i<n;i++)
{
if(HashTable[i].Key!=-1&&HashTable[i].indegree>=0)
{
haspos=HashTable[i].Key%n;
p=haspos;
while(p!=i)
{
if(HashTable[p].Key!=-1)
TMatric[p][i]=1;//表示p和i结点之间存在先后关系
HashTable[i].indegree++;
p=(p+1)%n;
}
}
}
}
void DeleteEdge(int p,int n)//删除结点的入度
{
for(int i=0;i<n;i++)
{
if(TMatric[p][i]==1)
{
//Q.pop();
TMatric[p][i]==0;
HashTable[i].indegree--;
if(HashTable[i].indegree==0)
Q.push(HashTable[i]);
}
}
}
int main()
{
int i,j,num;
scanf("%d",&num);
for(i=0;i<num;i++)
{
scanf("%d",&HashTable[i].Key);
HashTable[i].seq=i;
if(HashTable[i].Key>0){
if(HashTable[i].Key%num==i)
HashTable[i].indegree=-1;
else
HashTable[i].indegree=0;
}
}
calMatric(num);
vector<int>topNum;
int tmp=0;
//把当前度为0的压入优先队列
for(i=0;i<num;i++)
{
if(HashTable[i].Key!=-1)
if(HashTable[i].indegree==-1)
Q.push(HashTable[i]);
}
while(!Q.empty())
{
HashNode h;
h=Q.top();
topNum.push_back(h.Key);
Q.pop();//就是这里放到了DeleteEdge()函数的下方出错
DeleteEdge(h.seq,num);
}
//printf("%d\t",topNum[0]);
for(i=0;i<topNum.size();i++)
printf(" %d\t",topNum[i]);
system("pause");
}