Hash Without Collisions

We could consider the predefined function hash() from Python but, in order to ensure replicability, we define instead the following very simple hash function on strings. Given a positive integer MOD that we call, of course, the modulus,

h = lambda s, MOD: sum(ord(c) for c in s) % MOD

How many strings, among a given set of them, can we pick up without incurring in collisions under h? Which strings form the maximal set(s) with this property?

You must write a program that receives the value of MOD and a sequence of strings and finds sets of strings from the sequence within which the strings do not have any collision. These sets must be as large as possible. For instance, for MOD = 7, the words "No" and "seguinte" both hash to zero, so at most one of them can be chosen; likewise "dia" and "morreu" both hash to 1 whereas "ninguem" hashes to 6.

Input

First comes the positive integer MOD, then a sequence of words separated by spaces or newlines and distributed among lines in an unpredictable manner. There may be word repetitions in the input: these are to be ignored as we work with sets of words as we said.

Output

All the sets of the maximum possible size, made of words taken from the sequence, where the hash function h does not generate collisions at all inside each set.

Observation

The sets can be printed in any order and the elements inside them can be printed in any order too. Separate the set elements by a space and print each set in a line as in the examples.

Problem information

Author: José Luis Balcázar

Generation: 2026-01-25T13:27:15.489Z

© Jutge.org, 2006–2026.
https://jutge.org