Загрузка данных


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

int main() {
    vector<pair<string, string>> rules;
    string a, b;
    while (cin >> a >> b) {
        rules.push_back({a, b});
    }

    if (rules.empty()) return 0;

    bool good[256] = {false};

    for (int i = 0; i < 256; i++) {
        for (auto &p : rules) {
            bool ok = true;
            for (char c : p.second) {
                if (c >= 'A' && c <= 'Z' && !good[(unsigned char)c]) ok = false;
            }
            if (ok) good[(unsigned char)p.first[0]] = true;
        }
    }

    bool used[256] = {false};
    used[(unsigned char)rules[0].first[0]] = true;

    for (int i = 0; i < 256; i++) {
        for (auto &p : rules) {
            if (used[(unsigned char)p.first[0]] && good[(unsigned char)p.first[0]]) {
                for (char c : p.second) {
                    if (c >= 'A' && c <= 'Z' && good[(unsigned char)c]) {
                        used[(unsigned char)c] = true;
                    }
                }
            }
        }
    }

    for (auto &p : rules) {
        if (used[(unsigned char)p.first[0]] && good[(unsigned char)p.first[0]]) {
            bool ok = true;
            for (char c : p.second) {
                if (c >= 'A' && c <= 'Z' && !good[(unsigned char)c]) ok = false;
            }
            if (ok)
                cout << p.first << " " << p.second << endl;
        }
    }

    return 0;
}