Cod sursa(job #2658699)

Utilizator andrei.arnautuAndi Arnautu andrei.arnautu Data 14 octombrie 2020 20:16:17
Problema NFA Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.71 kb
/**
  *  Worg
  */
#include <set>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>

std::ifstream fin("nfa.in"); std::ofstream fout("nfa.out");

int n, m, k, s, q;
std::vector<bool> is_final_state;
std::vector<std::vector<std::pair<int, char> > > transitions;

void read_input() {
   fin >> n >> m >> k >> s;
   is_final_state = std::vector<bool>(n + 1, 0);
   transitions.resize(n + 1);

    for (int i = 0; i < k; i++) {
        int x; fin >> x;
        is_final_state[x] = 1;
    }

    for (int i = 0; i < m; i++) {
        int a, b; fin >> a >> b;
        char c; fin >> c;
        transitions[a].emplace_back(b, c);
    }

    fin >> q;
}

void solve_query() {
    std::string word; fin >> word;

    std::vector<bool> is_next(n + 1, 0);
    std::vector<int> current_states(n);
    current_states[0] = s;
    int no_current_states = 1;

    for (char c : word) {
        for (int i = 0; i < no_current_states; i++) {
            for (auto& edge : transitions[current_states[i]]) {
                if (edge.second == c) {
                    is_next[edge.first] = true;
                }
            }
        }

        no_current_states = 0;
        for (int i = 1; i <= n; i++) {
            if (is_next[i]) {
                current_states[no_current_states++] = i;
            }
            is_next[i] = false;
        }

        if (no_current_states == 0) {
            break;
        }
    }

    for (int i = 0; i < no_current_states; i++) {
        if (is_final_state[current_states[i]]) {
            fout << "1\n";
            return;
        }
    }

    fout << "0\n";
}

int main(int argc, char **argv) {
    read_input();
    for (int i = 0; i < q; i++) {
        solve_query();
    }
    return 0;
}