题解:P17414 「IXOI R3」贴吧 82 号

· · 题解

一般来说基础赛的 T2 都是巧思题(?)

若题解中出现任何如描述上/思路上/代码上的任何方面的问题,欢迎在评论区中反馈,我会在评论区中解答。

一、思路

首先题意很清楚了,无需赘述。

想到如下结论:

  1. 对于一个 \texttt{01} 字符串 s,最左边的 \texttt{0} 一定要进行操作(显然)。这是本题的核心思路。

  2. 选择正整数 x 进行操作后,不会影响到 x 号位置前面的字符。这个本质上和第一条是相同的。

那么,我们每次选择最左边 \texttt{0} 的位置进行操作,否则最左边的 \texttt{0} 将永远不会变成 \texttt{1};应用第二条结论,这么操作并不会影响前面已经全 \texttt{1} 的部分。那么我们遍历一遍,同时直接进行修改操作,进行一个类似质数筛的操作就行了。

二、代码

为防止影响观感,我的 IO 模板放在折叠框内部。

#include <bits/stdc++.h>

using namespace IO;
using namespace std;
const int N = 1e5 + 10;

char s[N];
int n;

int main() {
    read(n);
    scanf("%s", s + 1);
    int ans = 0;
    for (int i = 1; i <= n; i++) {
        if (s[i] == '0') {
            ans++;
            for (int j = i; j <= n; j += i) {
                if (s[j] == '0') s[j] = '1';
                else s[j] = '0';
            }
        }
    }
    write(ans);
    return 0;
}

:::info[Code]

namespace IO{
    void file() {
        freopen("input.in", "r", stdin);
        freopen("output.out", "w", stdout);
    }

    #define gc getchar
    #define pc putchar

    template <typename T>
    inline void read(T &x) {
        x = 0;
        bool f = 0;
        T s = 1;
        char ch = gc();
        while (!isdigit(ch) && ~ch) {
            f = (ch == '-');
            ch = gc();
        }

        while (isdigit(ch)) {
            x = (x << 3) + (x << 1) + (ch - 48);
            ch = gc();
        }

        if (ch == '.') {
            ch = gc();
            while (isdigit(ch)) {
                s *= 0.1;
                x += (ch - 48) * s;
                ch = gc();
            }
        }
        if (f) x = -x;
    }

    template <typename T>
    void write(T x) {
        if (x < 0) {
            pc('-');
            x = -x;
        }

        if (x >= 10) write(x / 10);
        pc(x % 10 + 48);
    }

    using std::string;
    inline void read(string &s) {
        s.clear();
        char ch = gc();
        while (isspace(ch)) ch = gc();
        while (!isspace(ch) && ~ch) s += ch, ch = gc();
    }

    inline void read(char &ch) {
        ch = gc();
        while (isspace(ch)) ch = gc();
    }

    inline void write(const string s) {
        for (auto ch : s) pc(ch);
    }

    inline void write(const char ch) {
        pc(ch);
    }

    inline void write(const double x) {
        printf("%.3Lf", (long double)x);
    }

    inline void write(const char *s) {
        while (*s) pc(*(s++));
    }

    template <typename T, typename ...t>
    void read(T &x, t &...y) {
        read(x);
        read(y...);
    }

    template <typename T, typename ...t>
    void write(T x, t ...y) {
        write(x);
        write(y...);
    }
}

:::