#P9507. [BalkanOI 2018] Popa
[BalkanOI 2018] Popa
Background
Translated from BalkanOI 2018 Day 2 T2 “Popa”.
"He's an outlaw and he's famous
Andrii Popa the courageous.
Day and night he rides,
He takes his tribute from the main road
And everywhere in the country
The thief catchers are running away as fast as they can"
Problem Description
Ghiță has a sequence of positive integers indexed from . Since he is the King of the Carpathians, he wants to construct a binary tree with nodes numbered such that:
- The inorder traversal of the tree lists the node indices in increasing order. The inorder traversal of a binary tree is the concatenation, in order, of the inorder traversal of the subtree rooted at the left child of the root (if it exists), the index of the root, and the inorder traversal of the subtree rooted at the right child of the root (if it exists).
- If is the parent of node , then divides .
A binary tree is a tree structure where each node has at most two children, called the left child and the right child.
Unfortunately, the famous outlaw Andrii Popa stole the sequence , so Ghiță cannot access it directly. However, for any two contiguous subarrays and , he can use the most advanced technology (his phone) to determine whether is equal to , where denotes the greatest common divisor of . Unfortunately, this technology is very expensive—if Ghiță uses it more than times, he will have to pay a huge fine. Please help him construct the desired tree using this technology at most times. It is guaranteed that this is possible. Any valid construction will be accepted.
Interaction
This problem only supports interactive solutions via functions in C++. The contestant’s code does not need to and must not include popa.h.
You need to implement the following function:
int solve(int N, int* Left, int* Right);
The function must return the root of the tree, and set Left[i] and Right[i] to be the left child and the right child of node , respectively. If node has no left child, then Left[i] should be set to . If node has no right child, then Right[i] should be set to . Left and Right point to two already-allocated arrays of length exactly .
The function solve will be called at most times in a single run. We suggest using global variables carefully.
You may call the following function (note that you must declare this function in your code):
int query(int a, int b, int c, int d);
This function returns if and only if , where . Otherwise it returns .
Example
For example, if , one possible interaction process is as follows:
Call to solve |
Call to query |
After calling solve |
|---|---|---|
solve(6, Left, Right) |
||
query(0, 1, 3, 5) returns |
||
query(4, 5, 1, 3) returns |
||
solve returns ; Left points to ; Right points to |
In the example, the tree King Ghiță wants is shown in the figure below.

Input Format
See “Interaction”.
Output Format
See “Interaction”.
Hint
Constraints
| Subtask ID | Limits | Score |
|---|---|---|
Translated by ChatGPT 5