This page is still under construction.

Parts of this page are still being built. What you see may change.

Robot Movement

Time limit2sMemory limit512 MB

Summary
A robot walks on an infinite grid following a fixed-length string of U, D, L, R moves. Change at most M characters to maximize how many times it returns to the origin.
Level

Medium6 of 10

Topics
Dynamic programming, String, Implementation, Brute force
Solved
No attempts yet

Problem

A robot stands on an infinitely large grid board. The board is divided into cells of size 1×1, and every cell is named by a coordinate (x,y)(x, y). The robot occupies one cell, and it starts at (0,0)(0, 0).

The robot comes with a program, a string of operations written with the letters U, D, L, and R. U moves the robot one cell up, D one cell down, L one cell left, and R one cell right. When the power goes on, the robot performs the programmed operations one at a time from the front. After the last operation it stops moving and turns itself off.

The robot claps every time it arrives at cell (0,0)(0, 0). You want to rewrite the program so that the number of visits to (0,0)(0, 0) is as large as possible. You may change at most MM operations. One change means picking a single character of the program and replacing it with a different character. Inserting a character or deleting one is not allowed.

The starting position (0,0)(0, 0) is not counted as a visit. Only a moment right after an operation, with the robot standing on (0,0)(0, 0), counts.

Given the operation string SS and the integer MM, write a program that finds the maximum number of visits to (0,0)(0, 0).

Input

The first line contains the program SS of the robot. SS consists only of the letters U, D, L, and R. The second line contains the integer MM.

Let LL be the length of SS. Then 2≤L≤3002 \le L \le 300 and 0≤M≤L0 \le M \le L.

Output

Print on the first line the maximum number of visits to (0,0)(0, 0) that at most MM changes can produce.

Hint

When SS is UULRRLLL and MM is 1, changing the first U into D gives three visits to (0,0)(0, 0). Changing the second U into D also gives three visits.

Examples5

  1. Example 1

    Input
    UULRRLLL
    1
    
    Expected output
    3
    
  2. Example 2

    Input
    ULDR
    0
    
    Expected output
    1
    
  3. Example 3

    Input
    ULDR
    2
    
    Expected output
    2
    
  4. Example 4

    Input
    ULDRRLRUDUDLURLUDRUDL
    4
    
    Expected output
    8
    
  5. Example 5

    Input
    UD
    1
    
    Expected output
    1