Under construction

Still being built. Things may change

Discount Event

Time limit4sMemory limit1024 MB

Summary
Given a weighted tree, for each query (X, Y) set every edge on the X to Y path to cost 0 and output the largest distance between any two cities.
Level

Hard8 of 10

Topics
Tree, Dynamic programming, DFS
Solved
No attempts yet

Problem

The country consists of NN cities and N−1N-1 roads. The cities are numbered from 11 to NN, and the roads are numbered from 11 to N−1N-1. Road ii connects cities AiA_i and BiB_i in both directions, and traveling along it costs WiW_i. For any two cities, you can travel between them using one or more roads.

The distance between two cities is the minimum cost of getting from one city to the other by using one or more roads.

You are the president of a road company, and you plan a discount event for the holidays. There are QQ plans. In plan ii, every road on the shortest path from city XiX_i to city YiY_i is discounted so that its cost becomes 0. For each plan, output the maximum distance between two cities.

Input

The first line contains the number of cities NN. Each of the next N−1N-1 lines contains three integers AiA_i, BiB_i, and WiW_i, separated by spaces. These are the two cities connected by road ii and the travel cost of that road.

The next line contains the number of plans QQ. Each of the next QQ lines contains two integers XiX_i and YiY_i, separated by a space, which describe plan ii.

Output

Print QQ lines. The ii-th line contains the answer for plan ii.

Constraints

  • 2≤N≤100 0002 \le N \le 100\,000
  • 1≤Ai,Bi≤N1 \le A_i, B_i \le N (1≤i≤N−11 \le i \le N-1)
  • Ai≠BiA_i \ne B_i (1≤i≤N−11 \le i \le N-1)
  • 1≤Wi≤1091 \le W_i \le 10^9 (1≤i≤N−11 \le i \le N-1)
  • The given country forms a valid tree.
  • 1≤Q≤100 0001 \le Q \le 100\,000
  • 1≤Xi,Yi≤N1 \le X_i, Y_i \le N (1≤i≤Q1 \le i \le Q)
  • Xi≠YiX_i \ne Y_i (1≤i≤Q1 \le i \le Q)

Examples4

  1. Example 1

    Input
    5
    1 2 1
    1 3 2
    2 4 4
    2 5 2
    3
    1 4
    3 5
    5 4
    
    Expected output
    4
    4
    3
    
  2. Example 2

    Input
    5
    1 2 2
    1 3 3
    1 4 5
    1 5 4
    3
    1 2
    1 4
    4 5
    
    Expected output
    9
    7
    5
    
  3. Example 3

    Input
    8
    1 2 3
    1 3 5
    2 4 5
    2 5 3
    2 6 6
    6 7 1
    6 8 2
    7
    1 2
    1 3
    2 4
    2 5
    2 6
    6 7
    6 8
    
    Expected output
    13
    13
    16
    16
    13
    16
    15
    
  4. Example 4

    Input
    7
    1 2 3
    1 3 4
    2 4 2
    2 5 1
    3 6 6
    3 7 2
    6
    1 2
    1 3
    1 4
    1 5
    1 6
    1 7
    
    Expected output
    12
    11
    11
    12
    7
    11