公式

B - Ticket Gate Log 解説 by en_translator


Scan \(S\) from the front to find at least how many operations are required to make the string up to the current position satisfy the condition.

Inspect the characters of \(S\) from the front while maintaining the next character \(t\) that needs to appear (initially \(t=\)i).

If the current character in \(S\) coincides with \(t\), it always satisfy the condition. Flip \(t\) (from i to o or o to i), and proceed to the next character.

If the current character is different from \(t\), we need to insert \(t\) right before the current character. By this operation, the string up to the current position satisfies the condition. Add \(1\) to the answer, and proceed to the next character of \(S\) without altering \(t\).

Finally, if the final character of \(S\) is i, then we need to insert o after that, so add \(1\) to the answer.

Sample code (Python)

S = input()
ans = 0
target = 'i'
for c in S:
    if c == target:
        target = 'o' if target == 'i' else 'i'
    else:
        ans += 1
if target == 'o':
    ans += 1
print(ans)

Sample code (C++)

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

int main() {
    string S;
    cin >> S;
    int ans = 0;
    char target = 'i';
    for (char c : S) {
        if (c == target) {
            target = target == 'i' ? 'o' : 'i';
        } else {
            ++ans;
        }
    }
    if (target == 'o') ++ans;
    cout << ans << endl;
}

投稿日時:
最終更新: