Perfect Hash
Time limit1sMemory limit128 MB
For each line of up to 13 short words, find the smallest positive integer C so the hash floor(C/w) mod n is collision free, and print C after echoing the input line.
- Level
Hard8 of 10
- Topics
- Hash map, Math, Brute force, Implementation
- Solved
- No attempts yet
Problem
Perfect Software, Inc. has a government contract to scan text flowing through a high-speed network for certain words. The system checks each word against a group of small perfect hash tables, and your task is to build the perfect hash function for each table.
A perfect hash function maps every input directly into a fully occupied table (no collisions and no empty slots). The hash function has the form , where:
- is a positive integer you must discover,
- is the integer representation of an input word, and
- is the length of the table (the number of words in the list).
must be as small as possible. Here is the floor of : the largest integer that is .
Finding . Let be the word values, sorted so that . Find the smallest positive integer such that
The smallest such is always a multiple of at least one element of .
A useful observation: if for some pair (a collision), then neither of those two floor values can change until reaches at least
so no smaller can resolve that collision. Because every collision must be resolved, it is efficient to advance to the largest of these thresholds over all current collisions and test again.
Encoding a word. Convert each word to a number by processing its letters from left to right. Treat 'a' as 1, 'b' as 2, , 'z' as 26, using 5 bits per letter (shift left by 5, i.e. multiply by 32, before adding the next letter). Thus 'a' and 'bz' .
Input
The input is a series of word lists, one per line, until end-of-file. Each line has between two and thirteen words, each at most five lowercase letters, separated by one or more spaces. Every line contains at least one single-letter word.
Output
For each word list, print the input line, then on the next line print the value of for that list's hash function. Print a blank line between the answers for consecutive lists. always fits in a signed 32-bit integer.