#PS0000163. Đoạn đi bộ quay về điểm cũ (Shortest Closed Walk)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Đ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 on a plane. A string of length 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 . The second line contains the string of moves.
Output
Print the minimum qualifying length, or -1 if none exists.
Subtasks
- Subtask 1 (20 points): ; ; all characters belong to
U,D,L,R. - Subtask 2 (30 points): ; ; all characters belong to
L,R. - Subtask 3 (50 points): ; ; 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.