Description

Hard

The Quantum Entanglement Network

Scientists are building a quantum communication network connecting n particles. Each particle has a spin value (0 or 1).

To establish a quantum link between two particles, the energy cost equals the distance between them. However, a link can only be formed between particles with different spin values (0 and 1).

Find the minimum total energy required to connect all particles into a single network where every particle can communicate with every other particle (directly or indirectly).

If it's impossible to connect all particles, return -1.

Input Format

The first line contains an integer n, the number of particles. The next n lines each contain three integers: x, y (coordinates), and spin (0 or 1). Distance between two particles is |x1-x2| + |y1-y2| (Manhattan distance).

Output Format

Print the minimum total energy, or -1 if impossible.

Examples

Example 1

Input
4 0 0 0 1 0 1 0 1 1 1 1 0
Output
3
ExplanationConnect (0,0,0)-(1,0,1) cost 1, then (1,0,1)-(1,1,0) cost 1, then (0,1,1)-(1,1,0) cost 1. Total = 3.

Example 2

Input
2 0 0 0 1 1 0
Output
-1
ExplanationBoth particles have spin 0, so no link can be formed.

Constraints

2 ≤ n ≤ 1000

0 ≤ x, y ≤ 10^6

spin is 0 or 1

Code

Login
Error

Case 1

Case 2

Input
4 0 0 0 1 0 1 0 1 1 1 1 0
Output
No output
Expected
3