蒟蒻的第一篇题解
前文:赛时写这题真的是弘文了,究竟是哪个神人把这玩意放T1啊,光写它就用了1hwww!!!
题目大意:
在字符串中选出一个长度至多为的字串,在中选出一个长度至多为的字串,要求拼接和后能得到最多的CDNL字串。
解题思路
蒟蒻用的是dp + 前缀和优化
计算的最大贡献
预处理:建两个数组和分别记录 s 和 t 中每个位置前CDNL的 数量。
然后定义、和分别存储t中长度不超过k的子串前面补 'C'/'CN'/'CND'能构成 "CDNL" 的最大数量。
计算的最大贡献
用滑动窗口和单调队列维护窗口内的最小值,计算 s 中每个位置结尾的子串最多包含多少个 CDNL,存入数组。
最后再枚举 s 的每个位置,结合 sval 和 t 的四种贡献情况,取最大值作为答案即可。
时间复杂度。
代码
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 5;
string s, t;
int n,m,k,T,tmax,tdnl,tnl,ans,tl,ps[MAXN],pt[MAXN],sval[MAXN];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); //关同步流好习惯
cin >> T;
while (T--) {
cin >> n >> m >> k;
cin >> s >> t;
memset(ps,0,MAXN);
for (int i = 0; i < n; ++i) {
if (i >= 3 && s[i-3] == 'C' && s[i-2] == 'D' && s[i-1] == 'N' && s[i] == 'L') {
ps[i+1] = ps[i] + 1;
}
else{
ps[i+1] = ps[i];
}
}
memset(pt,0,MAXN);
for (int i = 0; i < n; ++i) {
if (i >= 3 && t[i-3] == 'C' && t[i-2] == 'D' && t[i-1] == 'N' && t[i] == 'L') {
pt[i+1] = pt[i] + 1;
}
else {
pt[i+1] = pt[i];
}
}
tmax = 0;
for (int i = 0; i < n; ++i) {
int len = min(k, n - i);
int count = 0;
if (i + 3 <= n) {
count = pt[i + len] - pt[i + 3];
}
if (count > tmax) {
tmax = count;
}
}
tdnl = 0;
for (int i = 0; i <= n - 3; ++i) {
if (t[i] == 'D' && t[i+1] == 'N' && t[i+2] == 'L') {
int len = min(k, n - i);
int count = 0;
if (i + 3 <= n) {
count = pt[i + len] - pt[i + 3];
}
if (count > tdnl) {
tdnl = count;
}
}
}
tnl = 0;
for (int i = 0; i <= n - 2; ++i) {
if (t[i] == 'N' && t[i+1] == 'L') {
int len = min(k, n - i);
int count = 0;
if (i + 3 <= n) {
count = pt[i + len] - pt[i + 3];
}
if (count > tnl) {
tnl = count;
}
}
}
tl = 0;
for (int i = 0; i < n; ++i) {
if (t[i] == 'L') {
int len = min(k, n - i);
int count = 0;
if (i + 3 <= n) {
count = pt[i + len] - pt[i + 3];
}
if (count > tl) {
tl = count;
}
}
}
memset(sval,0,MAXN);
deque<int> dq;
for (int i = 0; i < n; ++i) {
int L = max(0, i - m + 1);
while (!dq.empty() && dq.front() < L + 3) {
dq.pop_front();
}
if (i >= 3) {
int j = i - 3;
if (j >= L) {
while (!dq.empty() && ps[dq.back()] >= ps[i]) {
dq.pop_back();
}
dq.push_back(i);
}
}
if (i >= 3 && !dq.empty()) {
sval[i] = ps[i+1] - ps[dq.front()];
}
else{
sval[i] = 0;
}
}
ans = tmax;
for (int i = 0; i < n; ++i) {
ans = max(ans, sval[i] + tmax);
if (s[i] == 'C' && m >= 1) {
ans = max(ans, sval[i] + tdnl + 1);
}
if (i >= 1 && s[i-1] == 'C' && s[i] == 'D' && m >= 2) {
ans = max(ans, sval[i] + tnl + 1);
}
if (i >= 2 && s[i-2] == 'C' && s[i-1] == 'D' && s[i] == 'N' && m >= 3) {
ans = max(ans, sval[i] + tl + 1);
}
}
cout << ans << '\n';
}
return 0;
}看到这了,点个赞再走吧!