题目描述
DESCRIPTION
Farmer John has arranged his () cows in a row and many of them are facing forward, like good cows. Some of them are facing backward, though, and he needs them all to face forward to make his life perfect.
Fortunately, FJ recently bought an automatic cow turning machine. Since he purchased the discount model, it must be irrevocably preset to turn () cows at once, and it can only turn cows that are all standing next to each other in line. Each time the machine is used, it reverses the facing direction of a contiguous group of cows in the line (one cannot use it on fewer than cows, e.g., at the either end of the line of cows). Each cow remains in the same *location* as before, but ends up facing the *opposite direction*. A cow that starts out facing forward will be turned backward by the machine and vice-versa.
Because FJ must pick a single, never-changing value of , please help him determine the minimum value of that minimizes the number of operations required by the machine to make all the cows face forward. Also determine , the minimum number of machine operations required to get all the cows facing forward using that value of .
INPUT FORMAT
Line : A single integer:
Lines : Line contains a single character, F
or B
, indicating whether cow is facing forward or backward.
OUTPUT FORMAT
Line : Two space-separated integers: and
SAMPLE INPUT
1 | 7 |
SAMPLE OUTPUT
1 | 3 3 |
HINT
For , the machine must be operated three times: turn cows , , and finally
题目大意
头牛排成一列 。每头牛或者向前或者向后。为了让所有牛都面向前方,农夫每次可以将 头连续的牛转向 ,求使操作次数最小的相应 和最小的操作次数 。 为朝前, 为朝后。
请在一行输出两个数字 和 ,用空格分开。
题解
因为一个点翻转两次和没有翻转的效果相同,所以对于每个点而言,只有 不翻转 和 翻转一次 两种可能性,将原序列的 B
和 F
分别抽象为 0
和 1
,构成01序列 ,对第的翻转操作就相当于 .
考虑贪心,顺序遍历每一位,如果当前位为 0
( B
),则将以该位为起点,长度为的子串全部翻转,判断是否能够将的每一位置为 1
( F
).
同时我们可以发现,使操作次数最小的相应 和最小的操作次数 并不具有单调性,只能通过枚举取得最优值,这样的时间复杂度是 并不能通过此题,必须再优化一维.
注意到贪心的过程中,我们对序列 进行的是 区间修改单点查询 的操作,同时异或运算支持前缀和的操作,这里可以使用差分进行优化,这样时间复杂度就能降到 了.
代码实现
1 |
|