Pretty Networks Inc. is a company that builds some curious artifacts whose purpose is to transform a set of input values in a given way. The transformation is determined by what they call a p-network. The following picture shows an example of a p-network.
In the general case, a p-network of order N and size M, has N horizontal wires numbered 1, 2, ..., N, and M vertical strokes. Each stroke connects two consecutive wires. There are no two different strokes touching the same point of any wire, and there is no stroke touching the leftmost or rightmost point of any wire. The above example is a p-network of order 5 and size 9.
The transformation determined by a p-network can be explained using a set of rules that govern the way a p-network should be traversed:
- start at the leftmost point of one wire, and go to the right;
- each time a stroke appears move to the connected wire, and keep going from left to right;
- stop when the rightmost point of one wire is reached.
If starting at wire i the traversing ends at wire j, we say that the p-network transforms i into j, and we denote this with i -> j. In the above example the p-network determines the set of transformations
{1 -> 3, 2 -> 5, 3 -> 4, 4 -> 1, 5 -> 2}.
Pretty Networks Inc. hired you to solve the following p-network design problem: given a number N and a set of transformations {1 -> i1, 2 -> i2, ..., N -> iN}, decide if a p-network of order N can be built to accomplish them and, in this case, give one that does it.
When there exists a solution with a certain size, in many cases there is another solution with a greater size. Scientists at Pretty Networks Inc. have stated that if there exists a solution for a p-network design problem, then there is a solution with size less than 4N^2. Therefore, they are interested only in solutions having a size below this bound.