Cuckoo for Hashing
Time limit2sMemory limit128 MB
Simulate cuckoo hashing insertions into two mod-indexed tables with displacement and print the final table contents.
- Level
Easy2 of 10
- Topics
- Simulation, Hash map, Array
- Solved
- No attempts yet
Problem
An integer hash table is a data structure that supports insert, delete and lookup of integer values in constant time. A traditional hash structure consists of an array of size (the hash table) and a hash function , which is usually . To insert a value into the table, you compute its hash value , which is the index of the location where goes. For example, if and the hash table has size , then goes into location . Of course, some other value may already sit in that location (, for example), which is a collision. Collisions can be handled in several ways, none of which this problem deals with.
Cuckoo hashing uses two hash tables and , each with its own hash function and . Insertion of a value proceeds as follows. You first try to store in at location . If that location is empty, store there and the insertion is done. Otherwise there is a collision to handle. Let be the value currently in that location. You replace with in , then try to store in at location . Again, if that location is empty, you store there and the insertion is done. Otherwise you replace the value there (call it ) with , and try to store back in at location , and so on. The process bounces back and forth between the two tables until an empty location turns up. A real implementation rehashes both tables once a certain number of swaps have occurred, but that never happens in this problem: every insertion is guaranteed to find an empty location.
Given the sizes of the two tables and a series of insertions, determine what each table holds at the end.
The name comes from the cuckoo bird, which lays its eggs in another bird's nest. The larger cuckoo chick hatches first and pushes the other chicks out of the nest, so it gets all the food. Gruesome but efficient.
Input
The input holds several test cases. Each test case starts with three positive integers , and , where and are the sizes of tables and , and is the number of insertions. The values to insert follow, in insertion order, and all of them are non-negative. Both tables start empty, and table uses the hash function . A line containing three zeros ends the input and is not a test case.
Constraints: ,
Output
For each test case, print Case k: on its own line, where counts the test cases starting at 1. Then, if holds at least one value, print Table 1 on its own line, followed by the non-empty locations of from the lowest index to the highest, one per line, in the form i:v, where is the index of the location and is the value stored there. Print Table 2 and the non-empty locations of the same way. If a table is empty, print nothing for it, not even its header.