Official
B - Ticket Gate Log Editorial
by
B - Ticket Gate Log Editorial
by
sotanishy
\(S\) を前から見て行って,今見ている場所までの文字列が条件を満たすような最小の操作回数を考えます.
次に現れる必要がある文字 \(t\)(最初は \(t=\)i
)を管理しながら,\(S\) を前から見ていきます.
\(S\) の今見ている文字が,\(t\) に一致するならば,すでに条件を満たします.\(t\) を反転させて(i
ならば o
に,o
ならば i
にする),\(S\) の次の文字を見ます.
\(S\) の今見ている文字が,\(t\) と異なるならば,\(t\) を今見ている文字の前に挿入する必要があります.この操作によって,今見ている文字までの条件が満たされます.このとき,答えに \(1\) を足し,\(t\) を変えずに \(S\) の次の文字を見ます.
最後に,\(S\) の最後の文字が i
ならば,その後ろに o
を挿入する必要があるので,答えに \(1\) を足します.
実装例 (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)
実装例 (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;
}
posted:
last update: