跳到正文

题解

题解:P14979 [USACO26JAN1] Sliding Window Summation S

eXquisite_crYstalZ约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年1月20日
收录
2026年9月16日
更新
2026年11月13日
篇幅
约 4 分钟
获赞
1
题目
P14979

版本

  1. v1当前

显然 ri=⨁j=ii+K−1bjr_i=\bigoplus_{j=i}^{i+K-1} b_j,因此 ri⊕ri+1=(⨁j=ii+K−1bj)⊕(⨁j=ii+K−1bj+1)=bi⊕bi+Kr_i \oplus r_{i+1} = (\bigoplus_{j=i}^{i+K-1} b_j) \oplus (\bigoplus_{j=i}^{i+K-1} b_{j+1})=b_i \oplus b_{i+K},即 bi+K=bi⊕ri⊕ri+1b_{i+K}=b_{i}\oplus r_i \oplus r_{i+1},形成 KK 条限制链,对于每一条链确定链头 bi(1≤i≤K)b_i(1 \le i \le K) 即可确定一整条链。

这时候贪心地对于每一个链头选择能让答案更优的方案即可?实际上这样做还漏了一个限制 r1=⨁j=1Kbjr_1=\bigoplus_{j=1}^{K} b_j,如果发现贪心选出来的方案不满足这个限制,还需要选择改动后对答案影响最小的一条链进行全链取反调整。

C++
#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;
}
原文
存档评论1 条抓取于