练习cf1550B. Maximum Cost Deletion

题目如下
B. Maximum Cost Deletion
time limit per test2 seconds
memory limit per test256 megabytes
You are given a string 𝑠 of length 𝑛 consisting only of the characters 0 and 1.

You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For example, if you erase the substring 111 from the string 111110, you will get the string 110. When you delete a substring of length 𝑙, you get 𝑎⋅𝑙+𝑏 points.

Your task is to calculate the maximum number of points that you can score in total, if you have to make the given string empty.

Input
The first line contains a single integer 𝑡 (1≤𝑡≤2000) — the number of testcases.

The first line of each testcase contains three integers 𝑛, 𝑎 and 𝑏 (1≤𝑛≤100;−100≤𝑎,𝑏≤100) — the length of the string 𝑠 and the parameters 𝑎 and 𝑏.

The second line contains the string 𝑠. The string 𝑠 consists only of the characters 0 and 1.

Output
For each testcase, print a single integer — the maximum number of points that you can score.

题目大意
现有长度为n的由“0”和“1”组成的数字串,每次可以删除连续的数字都相同的长度为l的子串,每次得分 𝑎⋅𝑙+𝑏;现在要求清空这个串,那么累计得分最大是多少。

题目分析
因为要求是清空这个串,那么无论每次的长度是多少,最终删除了长度为n的整个串,那么可以得到左半部分的得分固定为a * n;
但是右半部分是根据操作次数来计算,分为两种情况:
1.b >= 0时,最大化收益就要最大化操作次数,即为一个一个删,符合题意,一个元素的子串也是连续子串;
2.b < 0时,就要尽量减小操作次数,最小的操作次数由连续子串的个数决定;

最小操作次数,统计‘1’和‘0’分别的子连续断数,子段数更少的先操作清空后,最后一组默认连续,此时总操作数最小。

点击查看代码
int zero = 0, one = 0;
            if(s[0] == '0'){
                zero++;
            }else{
                one++;
            }
            for(int i = 1; i < n; i++){
                if(s[i] != s[i - 1]){
                    if(s[i] == '0'){
                        zero++;
                    }else{
                        one++;
                    }
                }
            }
            cnt = min(zero, one) + 1;
            sum = n * a + b * cnt;

完整代码

点击查看代码
#include <iostream>
using namespace std;

int main(){
    int t;
    cin >> t;
    while(t--){
        int n, a, b;
        cin >> n >> a >> b;
        string s;
        cin >> s;
        int cnt, sum;
        if(b >= 0){
            sum = n * (a + b);
        }else{
            int zero = 0, one = 0;
            if(s[0] == '0'){
                zero++;
            }else{
                one++;
            }
            for(int i = 1; i < n; i++){
                if(s[i] != s[i - 1]){
                    if(s[i] == '0'){
                        zero++;
                    }else{
                        one++;
                    }
                }
            }
            cnt = min(zero, one) + 1;
            sum = n * a + b * cnt;
        }
        cout << sum << endl;
    }
    return 0;
}

posted @ 2025-07-21 22:46  sirro1uta  阅读(9)  评论(0)    收藏  举报