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

#BS0000321. Ăn hết các ngôi sao (Packmen)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Ăn hết các ngôi sao (Packmen)

Packmen

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

A strip of n cells contains agents P, stars *, and empty cells denoted by dots. Agents start together. Each unit of time an agent may move one cell or wait; any star visited is eaten instantly. Agents may reverse, share cells, and must remain on the strip. Minimize the time until every star has been eaten.

Input

  • The first line contains integer nn, the number of cells.
  • The second line contains a string ss of length nn. Character ii is P for a Packman, * for a star, or . for an empty cell.

Output

Print one integer: the minimum time needed to eat every star.

Subtasks

  • Subtask 1 (20 points): 2≤n≤122\le n\le12; ∣s∣=n|s|=n; s∈{P,∗,.}ns\in\{P,*,.\}^n; at least one P and one *.
  • Subtask 2 (30 points): 2≤n≤1052\le n\le10^5; ∣s∣=n|s|=n; s∈{P,∗,.}ns\in\{P,*,.\}^n; exactly one P; at least one *.
  • Subtask 3 (50 points): 2≤n≤1052\le n\le10^5; ∣s∣=n|s|=n; s∈{P,∗,.}ns\in\{P,*,.\}^n; at least one P and one *.

Examples

Input 1

7
*..P*P*

Output 1

3

Explanation

The agent at cell 4 reaches cell 1; the one at 6 visits 5 then 7. Cell 1 is at distance 3 from the nearest agent.

Input 2

5
*P..*

Output 2

5

Explanation

From cell 2, the Packman takes one step to cell 1 and four more to cell 5. Visiting cell 5 first would take 3+4=7 steps. The first route is optimal.

Input 3

10
.**PP.*P.*

Output 3

2

Explanation

The Packmen at 4, 5 and 8 follow routes 4–3–2, 5–6–7 and 8–9–10. All four stars at 2, 3, 7 and 10 are eaten after two moves. Cell 2 is two moves from the nearest Packman, so this is optimal.