标签:pac include sum efi class lse ring cto ==
给定一个长度为 n 的 01 字符串,要这个字符串的每个 1 之间的距离都恰好为 k,求至少要修改几个字符。
设 \(f[i]\) 表示以 i 结尾(\(a[i]=1\))的合法情况至少需要修改多少个字符
转移是从 \(i-k \to i\),代价为 \([a[i]=0]\) 加上 \(a[i-k+1..i-1]\) 中 1 的数量
#include <bits/stdc++.h>
using namespace std;
#define int long long
void solve()
{
int n, k;
cin >> n >> k;
vector<int> a(n + 2);
vector<int> s(n + 2);
string str;
cin >> str;
for (int i = 1; i <= n; i++)
{
a[i] = str[i - 1] == ‘1‘;
s[i] = s[i - 1] + a[i];
}
auto sum = [&](int l, int r) -> int {
return s[r] - s[l - 1];
};
vector<int> f(n + 2);
for (int i = 1; i <= n; i++)
{
f[i] = s[i - 1] + (a[i] == 0);
}
for (int i = k; i <= n; i++)
{
f[i] = min(f[i], f[i - k] + (a[i] == 0) + sum(i - k + 1, i - 1));
}
int ans = sum(1, n);
for (int i = 1; i <= n; i++)
{
ans = min(ans, f[i] + sum(i + 1, n));
}
cout << ans << endl;
}
signed main()
{
ios::sync_with_stdio(false);
int t;
cin >> t;
while (t--)
{
solve();
}
}
[CF1353E] K-periodic Garland - dp
标签:pac include sum efi class lse ring cto ==
原文地址:https://www.cnblogs.com/mollnn/p/14408198.html