Utopia Divided
Time limit1sMemory limit128 MB
Assign 2N distinct numbers into N signed x/y pairs so the teleporter visits the given regions in order, choosing the lexicographically smallest guiding.
- Level
Medium7 of 10
- Topics
- Greedy, Backtracking, Implementation, Brute force
- Solved
- No attempts yet
Problem
Long ago the land of Utopia was split by war into four regions, separated by one vertical line (a north-south longitude) and one horizontal line (an east-west latitude). Their crossing point is the origin . A location is described by two numbers: how far east and how far north it lies from the origin, and either number may be negative. The four regions are:
- Utopia 1 — the northeast, where and ;
- Utopia 2 — the northwest, where and ;
- Utopia 3 — the southwest, where and ;
- Utopia 4 — the southeast, where and .

Citizens may not cross a border, so travel is done by a teleporter that starts at the origin . The teleporter is driven by code numbers: you are given distinct positive code numbers, each of which may be used exactly once. Using a code pair at the current point moves the teleporter to . You choose the order of the numbers, split them into pairs, and give each number a or sign; in each pair one number is the -displacement and the other is the -displacement.
You are given a sequence of region numbers. After the -th teleport the machine must land strictly inside the -th requested region (the signs of and must match that region); it may never come to rest on a border, i.e. never on a line or . Two or more consecutive requests may name the same region.
For example, with code numbers 7 5 6 1 3 2 4 8 and region sequence 4 1 2 1, the code pairs move the teleporter , which lie in Utopia respectively. Among all valid guidings for this input, that one is the lexicographically smallest.
A valid guiding always exists. When more than one exists, you must report the lexicographically smallest one, as defined in the output section.
Input
The first line contains an integer ().
The second line contains the distinct code numbers, integers with , separated by single spaces.
The third line contains the sequence of region numbers, each equal to , , , or , separated by single spaces.
Output
Print lines. The -th line describes the -th code pair as sx sy, where sx is the -displacement and sy is the -displacement. Each displacement is written with a leading sign (+ or -) immediately followed by its magnitude (no space after the sign), and the two displacements are separated by a single space.
A valid guiding always exists. When several valid guidings exist, print the lexicographically smallest one. Guidings are compared by the sequence of signed displacements in order — (at each step the -displacement comes before the -displacement) — where the integers are compared by value, so a more negative displacement is considered smaller.