CodeForces练习(2)

B. Chess Cheater

                                                     time limit per test1 second
                                                 memory limit per test256 megabytes
                                                        inputstandard input
                                                       outputstandard output

You like playing chess tournaments online.

In your last tournament you played n games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get 0 points. When you win you get 1 or 2 points: if you have won also the previous game you get 2 points, otherwise you get 1 point. If you win the very first game of the tournament you get 1 point (since there is not a "previous game").

The outcomes of the n games are represented by a string s of length n: the i-th character of s is W if you have won the i-th game, while it is L if you have lost the i-th game.

After the tournament, you notice a bug on the website that allows you to change the outcome of at most k of your games (meaning that at most k times you can change some symbol L to W, or W to L). Since your only goal is to improve your chess rating, you decide to cheat and use the bug.

Compute the maximum score you can get by cheating in the optimal way.

Input

Each test contains multiple test cases. The first line contains an integer t (1≤t≤20,000) — the number of test cases. The description of the test cases follows.

The first line of each testcase contains two integers n,k (1≤n≤100,000, 0≤k≤n) – the number of games played and the number of outcomes that you can change.

The second line contains a string s of length n containing only the characters W and L. If you have won the i-th game then si=W, if you have lost the i-th game then si=L.

It is guaranteed that the sum of n over all testcases does not exceed 200,000.

Output

For each testcase, print a single integer – the maximum score you can get by cheating in the optimal way.

解法思路:

第一次有点无从下手,但是沉下心来看看还是很容易理解的。

问题的关键 有两点:

第一:计算公式为: 赢得场数 × 2 - 单次赢得场数(也就是这次赢上次没赢)

第二:如何使得修改之后分数为最大?根据贪心算法,如果可以将两个胜场之间的负场全部填满,则额外获得的分数就越高(可以获得所有修改的负场的2点数+1(最后一个负场后一个的胜场成为了连胜))也就是 填空隙问题

于是问题改变为:

计算胜场和负场,计算单独获胜的胜场数量,创建一个容器,每个元素每一个连续负场的数目(记为间隔);

例如:WWLLWLLLWW

容器的元素为2,3,分别记录第一个连续负场LL和第二个连续负场LLL,胜场5,负场5,单独胜场2.

我们要做的就是先将k加到胜场数上(毕竟你(我?)作弊了嘛,修改了多少个就加多少个),接下来修改单独胜场数————把能修改的数目k和容器的每个元素比较,尽量去填满可以填满的元素(即a[i]<=k),多余的放入下一个,这样的话相当于多了k个连胜,少了k个单独获胜。既然如此,在这个操作之前对容器进行排序会更好。

然后修改单独获胜的场数,同时对k值进行--操作。计算公式还是 赢得场数 × 2 - 单次赢得场数

有两个 注意点

1.查找容器的最后一个元素要用 back()函数 访问,如果用下标访问可能会出现越界的问题,总之就是报错。

2.第一个为单独负场最后一个为单独负场 这两种情况比较特殊,它们在容器里都为1,所以排序后排在前面,但是填满它们获得的分数不是最大,所以修改为无穷大放在最后,除非实在没办法,否则一般不考虑先存放它们。

例如LWWLW,在只能修改一个的情况下修改第一个只能获得3点(因为第一个本身就是单独胜场或单独负场),修改第二个可以获得4点!
例如WWLWWL也是一样,修改第一个可以获得4点,第二个只能获得3点!

另附AC代码链接:https://paste.ubuntu.com/p/GxpjMcgK2W/

posted @ 2020-10-27 00:13  原切  阅读(44)  评论(0)    收藏  举报