PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#PS0000163. Đoạn đi bộ quay về điểm cũ (Shortest Closed Walk)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Đoạn đi bộ quay về điểm cũ (Shortest Closed Walk)

Shortest Closed Walk

Source: Phước Hưng OJ

Version: Phuoc Hung OJ Extended

Problem Statement

A walker starts at (0,0)(0,0) on a plane. A string ss of length nn describes the moves in order: U increases the y-coordinate by 1, D decreases it by 1, L decreases the x-coordinate by 1, and R increases it by 1. Choose a nonempty contiguous interval of moves whose position immediately before its first move equals the position immediately after its last move. Find the minimum number of moves in such an interval, or print -1 if none exists.

Input

The first line contains integer nn. The second line contains the string ss of nn moves.

Output

Print the minimum qualifying length, or -1 if none exists.

Subtasks

  • Subtask 1 (20 points): 1≤n≤5001\le n\le 500; ∣s∣=n|s|=n; all characters belong to U, D, L, R.
  • Subtask 2 (30 points): 1≤n≤2000001\le n\le 200000; ∣s∣=n|s|=n; all characters belong to L, R.
  • Subtask 3 (50 points): 1≤n≤2000001\le n\le 200000; ∣s∣=n|s|=n; all characters belong to U, D, L, R.

Example 1

Input

6
LURDLR

Output

2

Explanation

The first four moves return to (0,0). The last two moves L,R also return to (0,0). One move always changes position, so 2 is optimal.

Example 2

Input

4
UUUR

Output

-1

Explanation

Every move increases either x or y; no nonempty interval returns to its starting point.