#C6254. Maximum Manhattan Distance After Command Replacement

    ID: 49994 Type: Default 1000ms 256MiB

Maximum Manhattan Distance After Command Replacement

Maximum Manhattan Distance After Command Replacement

You are given a string of commands and an integer n. The string consists of characters 'U', 'D', 'L', and 'R', which represent moves Up, Down, Left, and Right respectively. Due to errors, exactly n of these commands can be replaced with any valid command of your choice. Your goal is to maximize the Manhattan distance from the starting point (0, 0) after performing all the commands.

The Manhattan distance between two points (x1, y1) and (x2, y2) is given by the formula:

\( |x1 - x2| + |y1 - y2| \)

In this problem, if the initial net vertical displacement is \(v = \text{count}(U) - \text{count}(D)\) and the initial net horizontal displacement is \(h = \text{count}(R) - \text{count}(L)\), then the original Manhattan distance is \(|v| + |h|\). After replacing exactly n commands optimally, the maximum added distance is \(2 \times n\), making the final answer:

\( |v| + |h| + 2 \times n \)

Your task is to implement a program that reads the input from standard input (stdin) and writes the result to standard output (stdout).

inputFormat

The input consists of two lines:

  • The first line contains a non-empty string representing the sequence of commands. It is guaranteed that the string only contains the characters 'U', 'D', 'L', and 'R'.
  • The second line contains an integer n which represents the number of commands that can be replaced.

outputFormat

Output a single integer, which is the maximum Manhattan distance that can be achieved after replacing exactly n commands optimally.

## sample
UDLR
1
2