CF132C 题解

· · 题解

思路

看见 n\le50,我们可以想到暴搜,我们需要 4 个参数:当前位置、当前字符下标、已使用修改次数、当前行使方向。对于 s_i=\text F 的情况,则有两种选择:不修改,则位置行驶一格,下标加 1,修改次数不变,行驶方向不变;修改,则位置不变,下标加 1,修改次数加 1,行使方向改变。对于 s_i=\text T 的情况,也有两种选择:不修改,则位置不变,下标加 1,修改次数不变,行驶方向改变;修改,则位置走一个,下标加 1,修改次数加 1,行驶方向不变。最后套个记忆化就行啦。

因为可以反复修改,所以在统计答案时不必修改次数 =n,而是只要和 n 同奇偶就行。

代码

# include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
int n, k, maxx;
string a;
bitset <2> vis[105][205][55];
void dfs (int step, int now, int use, int dir) {
    if (use > k || vis[step][now + 100][use][dir])
        return ;
    vis[step][now + 100][use][dir] = 1;
    if (step >= n) {
        if ((use ^ k ^ 1) & 1)
            maxx = max (maxx, abs (now));
        return ;
    }
    if (a[step] == 'F')
        dfs (step + 1, now + dir, use, dir), dfs (step + 1, now, use + 1, -dir);
    else
        dfs (step + 1, now, use, -dir), dfs (step + 1, now + dir, use + 1, dir);
    return ;
}
int main () {
    ios::sync_with_stdio (0);
    cin.tie (0);
    cout.tie (0);
    cin >> a >> k;
    n = a.size ();
    dfs (0, 0, 0, 1);
    cout << maxx;
    return 0;
}