题解:CF2176B Optimal Shifts

· · 题解

题解:CF2176B Optimal Shifts

题意简述

给定一个含至少一个 1 的二进制字符串 s,每次操作可选 d \in [1, n],将 s 循环右移 d 得 t,再将所有满足 t_j = 1 的位置在 s 中置为 1(已有 1 不变),花费 d。
目标是使 s 全为 1,求最小总花费。

思路分析

代码


#include <bits/stdc++.h>
using namespace std;

int n;
string s;

int main() {
    int T;
    cin >> T;
    while (T--) {
        cin >> n >> s;
        s = s + s; // 处理环形结构
        int ans = 0, t = 0;  // ans:最长连续 0 长度;t:当前连续 0 长度
        for (auto i : s) {
            if (i == '0') {
                t++;          // 遇到 0,当前连续长度 +1
            } else {
                t = 0;        // 遇到 1,连续 0 段中断,重置t
            }
            ans = max(ans, t); // 更新答案
        }
        cout << ans << endl;  // 输出
    }
    return 0;
}