Villages on a Highway
Time limit1sMemory limit128 MB
Given all pairwise distances between N villages on a line, reconstruct every possible set of consecutive gaps that reproduces exactly that multiset of distances.
- Level
Medium7 of 10
- Topics
- Backtracking, Combinatorics, Brute force
- Solved
- No attempts yet
Problem
Several villages lie in a row along a straight highway. The highway has no junctions, so all villages sit in order on a single line.
If you know the distances between neighbouring villages, you can compute the distance between any two villages. For example, if five villages A, B, C, D, E lie in a row and the neighbouring distances are given, you can build the full table of pairwise distances — of them in total.
Now consider the reverse: given all pairwise distances, write a program that determines the order of the villages and recovers the distances between neighbouring villages. Several arrangements may produce the same set of distances; in that case you must find all of them.
Input
The input consists of several test cases. The first line of each test case contains the number of villages (). It is followed by the pairwise distances, given as integers separated by spaces or newlines in non-increasing (descending) order. Each distance is a natural number between and inclusive, and the largest distance is the one between the leftmost and the rightmost village.
The last line contains a single , which marks the end of the input.
Output
For each test case, print the distances between neighbouring villages, separated by spaces. If several answers exist, regard each answer as a sequence of distances, sort the sequences lexicographically, and print them all, one per line. If no answer is possible, print nothing. After printing all answers of a test case, print ----- on its own line.