Under construction

Still being built. Things may change

Knight of the Tarot Cards

Time limit10sMemory limit512 MB

Summary
Find the minimum total price of tarot cards the knight must buy to reach (0, 0), where each card's values unlock new knight jumps.
Level

Hard8 of 10

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

Problem

Consider an infinite chessboard and a special knight whose move types can change given powerups. The knight is trying to reach square (0,0)(0, 0).

Some squares of the infinite chessboard have tarot cards on them. If the knight lands on a position (r,c)(r, c) with a tarot card on it, the knight can buy that card at that position. Each tarot card has a price and two integer values written on it. The tarot card with values aa and bb allows the knight to make these relative jumps:

(−a,−b)(-a, -b), (a,−b)(a, -b), (−a,b)(-a, b), (a,b)(a, b), (b,a)(b, a), (−b,a)(-b, a), (b,−a)(b, -a), (−b,−a)(-b, -a)

The knight keeps every card it buys and can make relative moves from any card it owns, any number of times. The knight pays only when it obtains a card. Jumps cost nothing. For example, if the knight buys a card with 3 and 2 and another card with 8 and 4, it may jump by (−2,3)(-2, 3), then by (8,4)(8, 4), and later by (−3,2)(-3, 2). The knight cannot make a jump (a,b)(a, b) until it arrives at a square with a tarot card showing aa and bb and buys that card.

Given the positions of the tarot cards and their prices, find the least amount the knight must pay to reach (0,0)(0, 0).

Input

Each test case begins with a line containing a single integer nn (1≤n≤1,0001 \le n \le 1,000), the number of tarot cards on the chessboard.

Each of the next nn lines describes a tarot card with five space-separated integers:

rr cc aa bb pp

Here −109≤r,c≤109-10^9 \le r, c \le 10^9 and 1≤a,b,p≤1091 \le a, b, p \le 10^9. The pair (r,c)(r, c) is the location of the card, aa and bb are its offset values, and pp is its price. The first tarot card is the knight's initial position. Multiple tarot cards may exist at the same location. The knight must have a tarot card to move.

Output

Output a single integer, the minimum cost for the knight to reach (0,0)(0, 0). Output −1-1 if the goal cannot be reached.

Examples3

  1. Example 1

    Input
    2
    3 3 2 2 100
    1 1 1 1 500
    
    Expected output
    600
    
  2. Example 2

    Input
    2
    2 0 2 1 100
    6 0 8 1 1
    
    Expected output
    100
    
  3. Example 3

    Input
    3
    1 0 100 50 100
    1 50 50 25 100
    26 0 20 30 123
    
    Expected output
    -1