Codeforces 814C 尺取法

传送门:题目

题意:

给一个长度为n的字符串,替换其中的m个字母,然后求替换后m个字母的最大长度。

题解:

q 2 10 5 n1500,直接暴力的化会超时,这里我们采用尺取法,算是一种优化的暴力吧。尺取法的意思就是我们拿一个区间,每次只考虑这个区间内答案,然后区间逐步往右移动,每次答案都取最大值,这样我们一定能获得最优解。一说到最优解,那么dp也一定可以做,是的,以后再填坑吧。

AC代码(尺取法):

#include<iostream>
#include <string>
using namespace std;
int main() {
    int n, T;
    string str;
    cin >> n >> str >> T;

    while (T--) {
        int x, ans = 0, r = 0, l = 0;
        char c;
        cin >> x >> c;
        for (int i = 0; i < n; i++) {
            if (str[i] != c)
                r++;
            while (r > x) {
                if (str[l] != c)
                    r--;
                l++;
            }
            ans = max(ans, i - l + 1);
        }
        cout << ans << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/shadandeajian/article/details/81666942
今日推荐