Under construction

Still being built. Things may change

Meeting Point

Time limit25sMemory limit1024 MB

Summary
Given an odd-sized hidden tree queried only by three-node median (meeting point) queries, find the node minimizing the total distance to all friends.
Level

Hard8 of 10

Topics
Tree, Divide and conquer, Implementation
Solved
No attempts yet

Problem

NN friends each live on their own node of a tree with NN nodes, where NN is odd. A tree is a connected graph with exactly N−1N-1 edges.

The friends want to meet at one node of the tree. They have decided to meet at the node that minimizes the sum of distances to all friends, and they asked you to find this optimal meeting point. The distance dist(a,b)\text{dist}(a,b) between two nodes aa and bb is the number of edges on the path between them. Formally, you want to find the node xx that minimizes ∑i=1ndist(x,i)\sum_{i=1}^{n} \text{dist}(x,i).

The friends do not remember what the tree looks like. They do remember this: given three different friends aa, bb, and cc, they meet (when only those three are present) at the node xx that minimizes dist(x,a)+dist(x,b)+dist(x,c)\text{dist}(x,a)+\text{dist}(x,b)+\text{dist}(x,c). Note that xx is not necessarily one of aa, bb, or cc.

The tree is not given in the input. You may ask up to Q−1Q-1 questions of the form: where do friends aa, bb, and cc meet? Use these questions to find the optimal meeting point.

Illustration of the example tree. Node 2 is the optimal meeting point.

Constraints

3≤N≤24 9993 \le N\le 24\,999

Examples1

  1. Example 1

    Input
    5 500000
    1 2
    2 3
    2 4
    4 5
    
    Expected output
    ? 1 2 4
    ? 1 3 4
    ? 1 4 5
    ? 1 2 3
    ? 1 2 5
    ! 3