题解:P14979 [USACO26JAN1] Sliding Window Summation S
eXquisite_crYstalZ · · 题解
显然
这时候贪心地对于每一个链头选择能让答案更优的方案即可?实际上这样做还漏了一个限制
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 200010;
int T;
int a[N], b[N];
struct Chain{
int cnt[2];
bool operator< (const Chain &B) const {
return abs(cnt[1] - cnt[0]) < abs(B.cnt[1] - B.cnt[0]);
}
}g[N];
char s[N];
int n, k, m;
void solve(){
scanf("%d%d", &n, &k);
scanf("%s", s + 1);
for(int i = 1; i <= k; i++) b[i] = 1;
for(int i = 1; i < n - k + 1; i++){
if(s[i] != s[i + 1]) b[i + k] = b[i] ^ 1;
else b[i + k] = b[i];
}
m = 0;
for(int i = 1; i <= k; i++){
m++;
g[m].cnt[0] = g[m].cnt[1] = 0;
for(int j = i; j <= n; j += k)
g[m].cnt[b[j]]++;
}
sort(g + 1, g + m + 1);
int tot = 0, ans = 0;
for(int i = 1; i <= m; i++){
if(g[i].cnt[0] > g[i].cnt[1]){
tot++;
ans += g[i].cnt[1];
}else ans += g[i].cnt[0];
}
if(tot % 2 != (s[1] - '0')) ans += abs(g[1].cnt[1] - g[1].cnt[0]);
printf("%d ", ans);
tot = 0, ans = 0;
for(int i = 1; i <= m; i++){
if(g[i].cnt[0] < g[i].cnt[1]){
tot++;
ans += g[i].cnt[1];
}else ans += g[i].cnt[0];
}
if(tot % 2 != (s[1] - '0')) ans -= abs(g[1].cnt[1] - g[1].cnt[0]);
printf("%d\n", ans);
}
int main(){
scanf("%d", &T);
while(T--) solve();
return 0;
}