projecthashing

#include <stdio.h>

int table[1000];/*save the inputed hash table*/

int indegree[1000];/*save every table-element's degree*/

int list[1000];/*save the element's correct input order*/

struct queuerecord

{

int front;

int rear;

int buf[1000];

};

typedef struct queuerecord queue;

queue q;/*define queue q*/

void mkempty()/*clean the queue q*/

{

q.front=0;

q.rear=-1;

}

void insertqueue(int p)/*insert the element's number into the right place*/

{

int i=0;

q.rear++;

q.buf[q.rear]=p;/*insert the number into the last place*/

for(i=q.rear;i>q.front&&table[q.buf[i-1]]>table[p];i--)/*find the element's right seat*/

q.buf[i]=q.buf[i-1];

q.buf[i]=p;/*insert the element's number*/

}

void topsort(int n)

{

int v,count=0,i;

while(q.rear>=q.front)

{

v=q.buf[q.front++];/*currently get the smallest element's number*/

list[count++]=table[v];/*save the element to the array list[]*/

for(i=0;i<n;i++)

if(indegree[i]>0)

if((i-table[i]%n>0&&table[i]%n<=v&&i>=v)||(i-table[i]%n<0&&((v+n>=table[i]%n&&v<=i)||(v>=table[i]%n&&v<=n))))/*table[v] is adjacency to table[i]*/

   if(--indegree[i]==0)/*if the element table[i]'s degree is 0 after dequeue table[v]*/

   insertqueue(i);

}

}

int main()

{

int N,i;

int num;/*count the elements' number*/

scanf("%d",&N);

while(N!=0)

{

num=0;

mkempty();

/*first clean the arrays*/

for(i=0;i<1000;i++)

{

table[i]=-1;

indegree[i]=0;

list[i]=0;

q.buf[i]=0;

}

for(i=0;i<N;i++)

{

scanf("%d",&table[i]);

if(table[i]>0)/*table[i] is not an empty cell*/

{

num++;

indegree[i]=i-table[i]%N;/*degree is equal to the length of the two cells*/

   if(indegree[i]<0)

   indegree[i]+=N;/*deal with the specail case*/

if(indegree[i]==0)

insertqueue(i);/*insert the degree's number into the queue*/

}

}

topsort(N);/*figure out the correct input order*/

/*print out*/

for(i=0;i<num-1;i++)

printf("%d ",list[i]);

printf("%d\n",list[i]);

scanf("%d",&N);

}

}

原文地址:https://www.cnblogs.com/chuxiking/p/1932933.html