Invisible Integers
Time limit5sMemory limit512 MB
Given up to 10 hints, each a walk order of distinct digits 1 to 9, find the shortest hidden integer sequence that can produce every hint.
- Level
Hard8 of 10
- Topics
- Backtracking, DFS, Implementation, Brute force
- Solved
- No attempts yet
Problem
Invisible integers is a guessing game. A player reconstructs a hidden sequence of integers between 1 and 9 from a few hints. Each hint is a sequence of distinct integers, built like this.
- Pick a starting position in the hidden sequence.
- Pick a direction, either left or right.
- Starting at the chosen position, walk through the integers of the hidden sequence in the chosen direction until you leave the sequence. Append every integer you meet to the end of the hint, skipping the integers already in the hint.
Find the length of the shortest hidden sequence consistent with all the given hints.
Input
The first line contains an integer (), the number of hints. Each of the next lines contains one hint: at least 1 and at most 9 distinct integers between 1 and 9, separated by spaces and terminated by the integer 0.
Output
Print -1 if no sequence is consistent with all the hints. Otherwise print a single integer, the length of the shortest such sequence.
Note
In the first example, is one shortest sequence consistent with the given hints.
- Hint comes from starting at the 3rd element and heading left.
- Hint comes from starting at the 6th element and heading right.
- Hint comes from starting at the 3rd element and heading right.
- Hint comes from starting at the 6th element and heading left.
- Hint comes from starting at the 1st element and heading right.