7-1 案例 整型关键字的散列映射

给定一系列整型关键字和素数P,用除留余数法定义的散列函数H(Key)=Key将关键字映射到长度为P的散列表中。用线性探测法解决冲突。

输入格式:

输入第一行首先给出两个正整数N(≤1000)和P(≥N的最小素数),分别为待插入的关键字总数、以及散列表的长度。第二行给出N个整型关键字。数字间以空格分隔。

输出格式:

在一行内输出每个整型关键字在散列表中的位置。数字间以空格分隔,但行末尾不得有多余空格。

 

输入样例:

4 5
24 15 61 88

输出样例:

4 0 1 3
const int IINF = 0x3f3f3f3f;
const long LINF = 0x3f3f3f3f3f3f3f3f;
const double EPS = 1.0e-9;
const long MOD = 1e9 + 7;
const int N = 2e5 + 100;

int m, n;
array<bool,N> check;
int findex(int x)
{
	x = x % n;
	int i = 1;
	while (x<n&&check[x])
	{
		x += i;
		i++;
	}
	if (x < n)
	{
		
		check[x] = 1;
		return x;
	}
	return -1;
}
int main(int args, char* argv[])
{
	//ios::sync_with_stdio(false);
	//cin.tie(nullptr);
	//cin.tie(nullptr);
	//auto start = std::chrono::steady_clock::now();
	//auto end = std::chrono::steady_clock::now();
	//std::chrono::duration<double> diff = end - start;
	//std::cout << diff.count() << " s\n";
	/*clock_t start = clock();
	clock_t end = clock();
	double time = (end - start) / CLOCKS_PER_SEC;*/
	
	cin >> m >> n;
	auto c=fill_n(check.begin(), m, false);
	for (int i = 0; i < m; i++)
	{
		int x;
		cin >> x;
		cout << findex(x) << " \0"[i == m - 1];
	}
	return 0;
}

 

posted @ 2022-12-15 07:40  noob-lian  阅读(116)  评论(0)    收藏  举报
Language: