This page is still under construction.

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

Wormholes

Time limit1sMemory limit128 MB

Summary
Given start, destination, and wormholes with entry-time constraints and time shifts, compute the earliest arrival time using a shortest-path style relaxation over travel distances and wormhole jumps.
Level

Medium6 of 10

Topics
Shortest path, Graph, Simulation
Solved
No attempts yet

Problem

A friend of yours has just built a spaceship and wants to explore space with it. On his first voyages he discovered that the universe is full of wormholes. A wormhole transports you instantly from its entry point to its exit point, and it can also shift you to a moment in the past or in the future.

Having mapped every wormhole together with its entry and exit points, you and your friend decide to fly to a distant destination and want to arrive as early as possible. Given your departure point, your destination, and all of the wormholes, determine the earliest time at which you can reach the destination.

Input

The first line contains an integer cc (1≤c≤2001 \le c \le 200), the number of test cases. Each test case is given as follows.

  • The first line contains two coordinate triples x0 y0 z0x_0\ y_0\ z_0 and x1 y1 z1x_1\ y_1\ z_1: the departure point and the destination.
  • The next line contains an integer nn (0≤n≤500 \le n \le 50), the number of wormholes.
  • Each of the next nn lines describes one wormhole with two coordinate triples xs ys zsx_s\ y_s\ z_s (entry) and xe ye zex_e\ y_e\ z_e (exit), followed by two integers tt and dd (−1000000≤t,d≤1000000-1000000 \le t, d \le 1000000): the creation time tt of the wormhole and the time shift dd applied when travelling through it.

All coordinates are integers with absolute value at most 1000010000, and no two of the listed points coincide.

Time starts at 00. The spaceship travels at speed 11, and the distance between two points is their Euclidean distance rounded up to the nearest integer, that is ⌈(Δx)2+(Δy)2+(Δz)2⌉\lceil \sqrt{(\Delta x)^2 + (\Delta y)^2 + (\Delta z)^2} \rceil. Passing through a wormhole is instantaneous: you may enter wormhole ii only at a time T≥tiT \ge t_i (you may wait before entering), and doing so places you at its exit point at time T+diT + d_i.

Output

For each test case, print a single line containing one integer: the earliest time at which you can arrive at your destination. This time may be negative.

Examples1

  1. Example 1

    Input
    2
    0 0 0 100 0 0
    2
    1 1 0 1 2 0 -100 -2
    0 1 0 100 1 0 -150 10
    0 0 0 10 0 0
    1
    5 0 0 -5 0 0 0 0
    
    Expected output
    -89
    10