Mowing the Field

Simulate the grid walk and report the smallest time gap between two visits to the same cell, or -1 when no cell repeats.

Easy3SimulationHash mapInterviewNo attempts yetTime limit2sMemory limit512 MB

Problem

Farmer John is reliable at almost every part of running his farm, with one exception: he is terrible at mowing the grass promptly or in any sensible order.

The farm is a large 2D grid of square unit cells. At time t=0t = 0 John starts in one of these cells and mows the grass there, so at first that cell is the only one with cut grass. The rest of his route is given by NN statements. For example, if the first statement is "W 10", then for times t=1t = 1 through t=10t = 10, that is the next 10 units of time, John steps one cell west at a time and mows the grass in every cell he passes. After finishing that statement he stands 10 cells west of where he started at time t=10t = 10, and the grass in every cell along the way is cut.

John works so slowly that some of the grass he cuts grows back before he is done. Grass cut at time tt reappears at time t+xt + x.

John may pass through the same cell several times, but he says he never stepped on a cell whose grass was still cut. That is, every time he steps on a cell, his previous visit to that same cell was at least xx units of time earlier, so the grass had already grown back.

Find the largest value of xx for which John's claim holds.

Input

The first line contains NN (1N1001 \le N \le 100). Each of the next NN lines contains one statement in the form "D S". D is a character giving a direction, where N is north, E is east, S is south and W is west. S is the number of steps taken in that direction, with 1S101 \le S \le 10.

Output

Print on one line the largest value of xx for which John never steps on a cell with cut grass. If John never visits any cell more than once, print -1.

Hint

In the sample, John steps at time 17 on a cell he already stepped on at time 7, so xx can be at most 10. Otherwise the grass from the first visit has not grown back yet. He also steps at time 26 on a cell he visited at time 2, so xx is also at most 24. The first constraint is the tighter one, so the largest xx is 10.