yukicoder No.154 - 市バス

解法

矛盾が起きるケースは

  1. 先頭から調べていて, GがWより多く出現した時,
  2. 先頭から調べていて, RがGより多く出現した時,
  3. 調べ終わったあと, GとRの数が釣り合っていない時,
  4. 最後にWが出てきてからそれに対応するであろうGが出現しなかった時,

の以上4つです.
あとはこれを素直にコーディングすれば良いです.

ソースコード

#include <iostream>
using namespace std;

int T;
string S;

/*
 * ありえないケースは
 * (1) w_cnt < g_cnt
 * (2) g_cnt < r_cnt
 * (3) 全て終わったあとに g_cnt != r_cnt
 * (4) 最後のWが出てから一度もGが出てきていない場合
 */
void Solve() {
    int w_cnt = 0, g_cnt = 0, r_cnt = 0;
    bool not_terminated = false;

    for (int i = 0; i < S.size(); i++) {
        if (S[i] == 'W') {
            w_cnt++;
            not_terminated = true;
        } else if (S[i] == 'G') {
            g_cnt++;
            not_terminated = false;
        } else {
            r_cnt++;
        }
        if (w_cnt < g_cnt || g_cnt < r_cnt) {
            cout << "impossible" << endl;
            return;
        }
    }
    if (!not_terminated && g_cnt == r_cnt) cout << "possible" << endl;
    else cout << "impossible" << endl;
}

int main() {
    cin >> T;

    while (T--) {
        cin >> S;

        Solve();
    }

    return 0;
}

感想

一発ACでした. やったぜ.