This page is still under construction.

Parts of this page are still being built. What you see may change.

City Driving

Time limit1sMemory limit128 MB

Summary
In a connected graph with N nodes and N edges, answer many shortest-path queries between pairs of nodes.
Level

Hard8 of 10

Topics
Tree, Graph, Shortest path, DFS
Solved
No attempts yet

Problem

You recently started spending your free time in San Francisco and realized that driving around the city is a huge pain. There are only NN locations that interest you, so you decide to make your driving easier. Because you have no GPS and cannot memorize many routes, you write down directions and travel times between NN pairs of locations. Each route is bidirectional (it takes the same time in either direction), and using only these routes you can travel between any two locations.

Now you are planning your weekend trips and, for QQ pairs of locations, you need to find the fastest way to travel between them using only the routes you wrote down.

Input

The input contains multiple test cases.

Each test case begins with a line containing a single integer NN (3≤N≤100,0003 \le N \le 100{,}000), the number of locations, which is also the number of routes.

Each of the next NN lines contains three integers uu, vv, and ww (1≤w≤1,0001 \le w \le 1{,}000): a route connecting locations uu and vv (0-indexed) that takes time ww in both directions.

The next line contains a single integer QQ (1≤Q≤10,0001 \le Q \le 10{,}000), the number of queries.

Each of the next QQ lines contains two integers uu and vv: find the minimum time to travel from location uu to location vv.

The input ends with a line containing N=0N = 0, which should not be processed.

Output

For each test case, print QQ lines. The ii-th line contains a single integer: the minimum time to travel between the ii-th queried pair of locations uu and vv.

Examples3

  1. Example 1

    Input
    7
    0 1 2
    0 2 3
    1 3 2
    2 3 8
    2 4 3
    3 5 1
    1 6 7
    3
    4 5
    0 6
    1 2
    0
    
    Expected output
    11
    9
    5
    
  2. Example 2

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

    Input
    4
    0 1 1
    1 2 1
    2 3 1
    3 0 1
    4
    0 2
    1 3
    0 0
    0 1
    0
    
    Expected output
    2
    2
    0
    1