#abc361d. D - Go Stone Puzzle
D - Go Stone Puzzle
Score : points
问题陈述
有 个单元格排成一行。设单元格 表示从左边数起的第 个单元格。
从单元格 到单元格 的每个单元格中都放置了一块石头。
对于每个 ,如果 是 W
,则单元格 中的石头是白色的;如果 是 B
,则单元格 中的石头是黑色的。
单元格 和单元格 是空的。
你可以执行以下操作任意次数(可能为零):
- 选择一对相邻的单元格,这两个单元格都包含石头,并将这两块石头移动到空的两个单元格中,同时保持它们的顺序。 更准确地说,选择一个整数 ,使得 并且单元格 和单元格 都包含石头。设 和 是空的两个单元格。将单元格 和单元格 中的石头分别移动到单元格 和单元格 。
确定是否可能达到以下状态,如果可能,找到所需的最小操作次数:
- 从单元格 到单元格 的每个单元格都包含一块石头,对于每个 ,如果 是
W
,则单元格 中的石头是白色的;如果 是B
,则单元格 中的石头是黑色的。
以上为大语言模型 kimi 翻译,仅供参考。
Problem Statement
There are cells arranged in a row. Let cell denote the -th cell from the left.
There is one stone placed in each of the cells from cell to cell .
For each , the stone in cell is white if is W
, and black if is B
.
Cells and are empty.
You can perform the following operation any number of times (possibly zero):
- Choose a pair of adjacent cells that both contain stones, and move these two stones to the empty two cells while preserving their order.
More precisely, choose an integer such that and both cells and contain stones. Let and be the empty two cells. Move the stones from cells and to cells and , respectively.
Determine if it is possible to achieve the following state, and if so, find the minimum number of operations required:
- Each of the cells from cell to cell contains one stone, and for each , the stone in cell is white if is
W
, and black if isB
.
Constraints
- is an integer.
- Each of and is a string of length consisting of
B
andW
.
Input
The input is given from Standard Input in the following format:
Output
If it is possible to achieve the desired state, print the minimum number of operations required. If it is impossible, print -1
.
Sample Input 1
6
BWBWBW
WWWBBB
Sample Output 1
4
Using .
to represent an empty cell, the desired state can be achieved in four operations as follows, which is the minimum:
BWBWBW..
BW..BWBW
BWWBB..W
..WBBBWW
WWWBBB..
Sample Input 2
6
BBBBBB
WWWWWW
Sample Output 2
-1
Sample Input 3
14
BBBWBWWWBBWWBW
WBWWBBWWWBWBBB
Sample Output 3
7