Under construction

Still being built. Things may change

Pleasant Tour

Time limit2sMemory limit512 MB

Summary
Given a tree of N rides, find an order visiting every ride once where each walking distance is no greater than the one before, using distance and subtree-count queries.
Level

Hard8 of 10

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

Problem

The largest amusement park in Jakarta has NN rides, numbered from 0 to N−1N-1. The rides are connected by N−1N-1 two-way paths, so for any two rides there is exactly one path between them. The paths are numbered from 0 to N−2N-2. Path ii connects rides A[i]A[i] and B[i]B[i], and walking along it takes one hour. To avoid crowding, every ride is connected to at most 3 paths.

You want to build a tour that visits every ride exactly once. Walking through several paths to get from one ride to the next is tiresome. To make the tour pleasant, the travel time from each ride to the next must not be longer than the travel time of the step before it. In other words, find a permutation P[0],P[1],…,P[N−1]P[0], P[1], \dots, P[N-1] of the integers from 0 to N−1N-1 such that for every 0<i<N−10 < i < N-1, the time to walk from P[i]P[i] to P[i+1]P[i+1] is not greater than the time to walk from P[i−1]P[i-1] to P[i]P[i].

You do not have the full map. You can ask the information center up to QQ questions. Each question has two parameters XX and YY, where 0≤X,Y<N0 \le X, Y < N. A question is one of the following two kinds.

  • How many hours does it take to walk from ride XX to ride YY? When X=YX = Y, the answer is 0.
  • Given XX and YY, how many rides ZZ satisfy this condition: to walk from ride XX to ride ZZ, you must pass through ride YY? Ride YY is included. When X=YX = Y, the answer is NN.

Constraints

  • 2≤N≤1000002 \le N \le 100000.
  • Q=400000Q = 400000.
  • Any two rides can reach each other through the paths.
  • Each ride is connected to at most 3 paths. (That is, it is an endpoint of at most 3 paths.)

Examples1

  1. Example 1

    Input
    2
    0 1
    
    Expected output
    0 1