5-18 Hashing - Hard Version (30分)

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

struct node
{
	int key, index;

	bool operator < (const node &nod) const
	{
		return nod.key < key;
	}
};

node initnode(int key, int index)
{
	node nod;
	nod.key = key;
	nod.index = index;

	return nod;
}

int main()
{
	int n;
	scanf("%d", &n);

	int hash[1010], i, indegree[1010];
	for(i = 0; i < n; i++)
	{
		scanf("%d", &hash[i]);

		if(hash[i] < 0)
		{
			indegree[i] = -1;
		}
		else
		{
			indegree[i] = 0;
		}
	}

	int curindex, j;
	vector<int> v[1010];

	for(i = 0; i < n; i++)
	{
		if(indegree[i] == -1)
		{
			continue;
		}

		curindex = hash[i] % n;
		indegree[i] = (i - curindex + n) % n;

		for(j = 0; j < indegree[i]; j++)
		{
			v[(curindex + j) % n].push_back(i);
		}
	}

	priority_queue<node> q;
	for(i = 0; i < n; i++)
	{
		if(indegree[i] == 0)
		{
			q.push(initnode(hash[i], i));
		}
	}

	int size, nextindex;
	vector<int> res;
	node curnod;

	while(q.empty() == false)
	{
		curnod = q.top();
		q.pop();

		res.push_back(curnod.key);

		size = v[curnod.index].size();
		for(i = 0; i < size; i++)
		{
			nextindex = v[curnod.index][i];
			indegree[nextindex]--;

			if(indegree[nextindex] == 0)
			{
				q.push(initnode(hash[nextindex], nextindex));
			}
		}
	}

	size = res.size();
	for(i = 0; i < size; i++)
	{
		if(i > 0)
		{
			printf(" ");
		}

		printf("%d", res[i]);
	}

	printf("\n");

	system("pause");
	return 0;
}

 

posted on 2025-11-29 15:00  王景迁  阅读(0)  评论(0)    收藏  举报

导航