All problems

Problem 498

Walking Robot Simulation

Medium · 20 pts · Array, Hash Table, Simulation

Problem

A robot starts at (0, 0) facing north (towards positive y). It receives a list of commands: -2 means turn left 90 degrees, -1 means turn right 90 degrees, and a value from 1 to 9 means move forward that many units, one unit at a time. Some grid points contain obstacles; if the next step would land on an obstacle, the robot stays where it is and skips the rest of that move command. Print the largest squared distance from the origin (x² + y²) that the robot reaches at any moment. Store the obstacles in a hash set for O(1) lookups.

Input

First line: N and M. Second line: the N commands. Next M lines: the coordinates x y of an obstacle.

Output

Print the maximum squared distance from the origin.

Constraints

1 <= N <= 10000; 0 <= M <= 10000; -30000 <= x, y <= 30000; (0, 0) is never an obstacle

Example input

5 1
4 -1 4 -2 4
2 4

Example output

65

Explanation

With commands 4 -1 4 -2 4 and an obstacle at (2, 4): the robot goes to (0, 4), turns right, is blocked at (1, 4) by the obstacle, turns left and walks to (1, 8). The largest squared distance is 1 + 64 = 65.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Robot Return to Origin Next: Tic-Tac-Toe Winner