Official

B - Ticket Gate Log Editorial by sotanishy


SS を前から見て行って,今見ている場所までの文字列が条件を満たすような最小の操作回数を考えます.

次に現れる必要がある文字 tt(最初は t=t=i)を管理しながら,SS を前から見ていきます.

SS の今見ている文字が,tt に一致するならば,すでに条件を満たします.tt を反転させて(i ならば o に,o ならば i にする),SS の次の文字を見ます.

SS の今見ている文字が,tt と異なるならば,tt を今見ている文字の前に挿入する必要があります.この操作によって,今見ている文字までの条件が満たされます.このとき,答えに 11 を足し,tt を変えずに SS の次の文字を見ます.

最後に,SS の最後の文字が i ならば,その後ろに o を挿入する必要があるので,答えに 11 を足します.

実装例 (Python)

Copy
  1. S = input()
  2. ans = 0
  3. target = 'i'
  4. for c in S:
  5. if c == target:
  6. target = 'o' if target == 'i' else 'i'
  7. else:
  8. ans += 1
  9. if target == 'o':
  10. ans += 1
  11. 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
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main() {
  4. string S;
  5. cin >> S;
  6. int ans = 0;
  7. char target = 'i';
  8. for (char c : S) {
  9. if (c == target) {
  10. target = target == 'i' ? 'o' : 'i';
  11. } else {
  12. ++ans;
  13. }
  14. }
  15. if (target == 'o') ++ans;
  16. cout << ans << endl;
  17. }
#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:



2025-04-05 (Sat)
20:46:11 +00:00