Delivery Route

Time limit1sMemory limit128 MB

Summary
Find the shortest 4-directional grid path that visits farms 1..N in order and back to farm 1, never stepping on any other farm's cell; output -1 if impossible.
Level

Hard8 of 10

Topics
BFS, Shortest path, Geometry, Implementation
Solved
No attempts yet

Problem

After several years of record milk production, Farmer John now operates an entire network of NN farms (1≤N≤1001 \le N \le 100). Farm ii is located at position (xi,yi)(x_i, y_i) in the 2D plane; all farm positions are distinct, and both xix_i and yiy_i are integers.

Farmer John needs your help planning his daily delivery route to bring supplies to the NN farms. Starting from farm 1, he plans to visit the farms in order (farm 1, then farm 2, then farm 3, and so on), and after visiting farm NN he returns to farm 1. It takes FJ one minute to make a single step north, south, east, or west. Moreover, FJ wants to visit each farm exactly once during his entire journey (except farm 1, which he of course visits twice). In other words, while travelling between two farms he may never step on the cell occupied by any other farm.

Please help FJ determine the minimum amount of time it will take him to complete his entire delivery route.

Input

  • Line 1: the number of farms, NN.
  • Lines 2..N+1N+1: line i+1i+1 contains two space-separated integers xix_i and yiy_i (1≤xi,yi≤1061 \le x_i, y_i \le 10^6).

Output

  • Line 1: the minimum number of minutes FJ needs to complete his delivery route, or −1-1 if there is no feasible route that visits every farm exactly once (except farm 1).

Hint

In the first example, FJ can complete his delivery route in 12 minutes: 2 minutes to go from farm 1 to farm 2, 5 minutes to go from farm 2 to farm 3 (circumventing farm 1), 3 minutes to go from farm 3 to farm 4, and then 2 minutes to return to farm 1.

Examples1

  1. Example 1

    Input
    4
    2 2
    2 4
    2 1
    1 3
    
    Expected output
    12