Cartesian Tree
Time limit2sMemory limit64 MB
Build the Cartesian tree whose inorder follows one key and heap order follows the other, printing parents and children, or NO when impossible.
Problem
Consider a special kind of binary search tree called a Cartesian tree. A binary search tree is a rooted ordered binary tree in which every node satisfies one condition: every node in its left subtree has a key smaller than the key of , and every node in its right subtree has a key larger than the key of .
Write for the left subtree of node , for its right subtree, and for its key. Then every node satisfies
- if then
- if then
A binary search tree is Cartesian when every node also carries an auxiliary key and those auxiliary keys satisfy the heap condition, that is,
- if is the parent of then
So a Cartesian tree is a rooted ordered binary tree in which every node carries a pair of keys and all three conditions above hold.
You are given a set of pairs. Build a Cartesian tree out of them, or decide that it is impossible.
Input
The first line contains an integer , the number of pairs to build the Cartesian tree from (). Each of the next lines contains two integers and . Every pair satisfies and . All main keys are distinct and all auxiliary keys are distinct, that is, and for .
Output
On the first line print YES if a Cartesian tree can be built out of the given pairs, or NO if it cannot. If it can, print the tree on the next lines. Nodes are numbered from 1 to in the order their pairs appear in the input. For each node print three numbers on one line: its parent, its left child and its right child. Print 0 when the node has no parent or no such child.
Only one tree can be built from the given input.