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