This page is still under construction.

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

Collecting Beepers

Time limit1sMemory limit128 MB

Summary
Given Karel's start and up to 8 beepers on a grid, find the shortest Manhattan-distance round trip visiting every beeper.
Level

Medium6 of 10

Topics
Dynamic programming, Bit manipulation, Graph, Brute force
Solved
No attempts yet

Problem

Karel is a robot living in a rectangular coordinate system where every position is given by a pair of integer coordinates (x,y)(x, y). A number of beepers are placed throughout her world, and Karel must pick all of them up. Karel can only move along the xx and yy axes, never diagonally. Moving to an adjacent position costs one unit of distance, so the travel distance between two positions equals their Manhattan distance (the sum of the absolute differences of their coordinates).

Karel starts at her starting position, must visit every position that holds a beeper, and then return to her starting position. Find the minimum total length of the path Karel travels. The beepers may be visited in any order.

Input

The first line contains the number of scenarios. Each scenario is given as follows:

  • A line with two integers: the size of the world (x-size and y-size).
  • A line with two integers xx and yy: Karel's starting position.
  • A line with one integer nn: the number of beepers.
  • nn following lines, each with two integers xx and yy: the coordinates of a beeper.

Output

For each scenario, print one line giving the minimum distance Karel must travel to leave her starting position, visit every beeper, and return to the starting position, in the form:

The shortest path has length D

where DD is the minimum distance.

Constraints

  • 1≤1 \le size of the world ≤9\le 9
  • 1≤1 \le number of beepers ≤8\le 8
  • 1≤x,y≤1 \le x, y \le size of the world

Examples2

  1. Example 1

    Input
    1
    10 10
    1 1
    4
    2 3
    5 5
    9 4
    6 5
    
    Expected output
    The shortest path has length 24
    
  2. Example 2

    Input
    1
    9 9
    1 1
    1
    5 5
    
    Expected output
    The shortest path has length 16