Under construction

Still being built. Things may change

Admissible Map

Time limit3sMemory limit512 MB

Summary
Count the substrings of a U/L/D/R string that, read row by row as a grid, form a map whose arrows make only cycles and stay inside the grid.
Level

Medium7 of 10

Topics
String, Hash map, String matching
Solved
No attempts yet

Statement

A map is a matrix consisting of symbols from the set of U, L, D, and R.

A map graph of a map matrix aa is a directed graph with n⋅mn \cdot m vertices numbered (i,j)(i, j) (1≤i≤n;1≤j≤m1 \le i \le n; 1 \le j \le m), where nn is the number of rows and mm is the number of columns. The graph has n⋅mn \cdot m directed edges (i,j)→(i+diai,j,j+djai,j)(i, j) \to (i + di_{a_{i,j}}, j + dj_{a_{i,j}}), where (diU,djU)=(−1,0)(di_U, dj_U) = (-1, 0), (diL,djL)=(0,−1)(di_L, dj_L) = (0, -1), (diD,djD)=(1,0)(di_D, dj_D) = (1, 0), and (diR,djR)=(0,1)(di_R, dj_R) = (0, 1). A map graph is valid when all edges point to valid vertices in the graph.

An admissible map is a map whose map graph is valid and consists of a set of cycles.

A description of a map aa is the concatenation of all rows of the map: the string a1,1a1,2…a1,ma2,1…an,ma_{1,1} a_{1,2} \ldots a_{1,m} a_{2,1} \ldots a_{n,m}.

You are given a string ss. Count the substrings of ss that can constitute a description of some admissible map. A substring is defined by a pair of indices pp and qq (1≤p≤q≤l1 \le p \le q \le l, where ll is the length of ss) and equals spsp+1…sqs_p s_{p+1} \ldots s_q. Two substrings are different when their index pairs (p,q)(p, q) differ, even if they spell the same string.

Input

The only line contains a string ss of at least 1 and at most 20,000 symbols, each U, L, D, or R.

Output

Print one integer: the number of substrings of ss that constitute a description of some admissible map.

Hints

In the first example, two substrings can constitute a description of an admissible map: RDUL as a 2×22 \times 2 matrix (pic. 1) and DU as a 2×12 \times 1 matrix (pic. 2).

In the second example, no substring works. For instance, reading RDRU as a 2×22 \times 2 matrix gives a graph that is not a set of cycles (pic. 3).

In the third example, three substrings RL, two substrings RLRL, and one substring RLRLRL work, and some of them work in more than one way. For instance, RLRLRL works as a 3×23 \times 2 matrix (pic. 4) and as a 1×61 \times 6 matrix (pic. 5).

Examples3

  1. Example 1

    Input
    RDUL
    
    Expected output
    2
    
  2. Example 2

    Input
    RDRU
    
    Expected output
    0
    
  3. Example 3

    Input
    RLRLRL
    
    Expected output
    6