Under construction

Still being built. Things may change

Teleport

Time limit2sMemory limit512 MB

Summary
Given N cities with coordinates, some special, travel costs Manhattan distance; special cities also connect by teleport costing T. Answer M shortest-path queries.
Level

Medium6 of 10

Topics
Graph, Shortest path, Math, Implementation
Solved
No attempts yet

Problem

There are NN cities on a two-dimensional plane. Some of the cities are special. The travel time from the city at (r1,c1)(r_1, c_1) to the city at (r2,c2)(r_2, c_2) is ∣r1−r2∣+∣c1−c2∣|r_1 - r_2| + |c_1 - c_2|. If both cities are special, you may also travel between them by teleport. A teleport takes TT time.

Given MM pairs of cities, find the minimum travel time for each pair.

Input

The first line gives the number of cities NN and the time a teleport takes TT.

The next NN lines give three integers s,x,ys, x, y describing the cities, in order from city 1 to city NN. If ss is 1, the city is special; if ss is 0, it is not special. (x,y)(x, y) is the coordinate of the city.

The next line gives MM, and the following MM lines each give two cities AA and BB.

Output

Print the minimum travel time from AA to BB, one value per line, over MM lines.

Constraints

  • 2≤N≤1,0002 \le N \le 1,000
  • 1≤T≤2,0001 \le T \le 2,000
  • 1≤M≤1,0001 \le M \le 1,000
  • 0≤x,y≤1,0000 \le x, y \le 1,000
  • A≠BA \neq B
  • No two cities share the same coordinate.

Examples2

  1. Example 1

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

    Input
    6 2
    1 1 1
    1 1 2
    1 1 3
    1 2 1
    1 2 2
    1 2 3
    6
    1 2
    2 3
    3 4
    4 5
    5 6
    6 1
    
    Expected output
    1
    1
    2
    1
    1
    2