题解:CF1778C Flexible String
_TwilightSnow_ · · 题解
Preface
好题。折磨了我近一个小时。
Solution
突破口肯定是在
可以搜索选取那些字母替换,并用
Code
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define PII pair<int, int>
#define VI vector<int>
#define sz(a) a.size()
#define all(a) a.begin(), a.end()
#define up(i, s, t) for (int i = s; i <= t; i++)
#define dw(i, s, t) for (int i = s; i >= t; i--)
int n, k, res;
string a, b;
VI col;
int st[27];
int solve() { // 计算贡献
// 1 + 2 + ... + len = len * (len + 1) / 2
int cnt = 0;
up(i, 0, n - 1) {
int r = i;
if (a[r] != b[r] && !st[a[r] - 'a']) continue;
while (r < n && (a[r] == b[r] || st[a[r] - 'a']))
r++;
cnt += (r - i) * (r - i + 1) / 2;
i = r - 1;
}
return cnt;
}
void dfs(int dep, int c) { // 搜到第 dep 种字母,替换了 c 个
if (c > k) return; // c > k 不合法状态
if (dep == sz(col)) { // 搜完了
res = max(res, solve());
return;
}
st[col[dep]] = 1; // 替换这个字母
dfs(dep + 1, c + 1);
st[col[dep]] = 0;
dfs(dep + 1, c); // 不替换
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int t; cin >> t;
while (t-- && cin >> n >> k >> a >> b) {
col.clear(), res = 0;
unordered_set<int> S; // 用 unordered_set 去重
up(i, 0, n - 1) {
if (!S.count(a[i] - 'a')) col.push_back(a[i] - 'a');
S.insert(a[i] - 'a');
}
dfs(0, 0), cout << res << '\n';
}
return 0;
}