Under construction

Still being built. Things may change

Swarm

Time limit10sMemory limit512 MB

Summary
Given a set of allowed compass directions, place all bees on one integer point minimizing the total number of moves.
Level

Medium7 of 10

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

Problem

A violent storm has scattered a swarm of bees across the coordinate plane. Each bee is now at some point with integer coordinates. All the bees want to gather at a single point, which must also have integer coordinates. The bees in this swarm share a genetic mutation, so they can fly only in certain directions. The allowed directions are a subset of the eight compass directions: the four cardinal directions and the four intercardinal directions (northeast, northwest, southeast, southwest). As usual, north is the direction of increasing yy and east is the direction of increasing xx.

In one step, one bee can move to a neighboring integer point in one of the allowed directions. For example, one step northeast moves a bee from (x,y)(x, y) to (x+1,y+1)(x+1, y+1), and one step west moves it from (x,y)(x, y) to (x−1,y)(x-1, y). Find the minimum total number of steps needed for all the bees to end up at the same point.


Illustration of the first example

Input

The first line contains an integer dd (1≤d≤81 \le d \le 8), the number of allowed directions.

The second line contains dd distinct strings separated by single spaces. Each string is one of N, NW, W, SW, S, SE, E, NE, which stand for north, northwest, west, southwest, south, southeast, east, and northeast, in that order.

The next line contains an integer nn (1≤n≤501 \le n \le 50), the number of bees.

The kk-th of the following nn lines contains integers xkx_k and yky_k (−106≤xk,yk≤106-10^6 \le x_k, y_k \le 10^6), the coordinates of the point where the kk-th bee is now. All bees are at distinct points.

Output

Print the minimum total number of steps. The input guarantees that all the bees can gather at one point.

Examples4

  1. Example 1

    Input
    3
    N NE NW
    5
    1 1
    5 1
    1 4
    3 3
    2 3
    
    Expected output
    13
    
  2. Example 2

    Input
    3
    N SE SW
    3
    -4 1
    -4 -2
    4 -2
    
    Expected output
    16
    
  3. Example 3

    Input
    6
    N E W SW NE NW
    3
    249 218
    443 -290
    231 -444
    
    Expected output
    1013
    
  4. Example 4

    Input
    3
    S SE NE
    4
    437 -368
    387 -47
    -422 136
    -407 -300
    
    Expected output
    2025