Cod sursa(job #2588244)

Utilizator Silviu.Stancioiu@gmail.comSilviu Stancioiu [email protected] Data 24 martie 2020 16:23:15
Problema NFA Scor 50
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.59 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <queue>

using namespace std;

struct Nod
{
    Nod()
    {
        start  = false;
        ending = false;
        links  = map<char, vector<int> >();
        nextNodes = vector<pair<int, char> >();
    }

    bool                     start;
    bool                     ending;
    map<char, vector<int> >  links;
    vector<pair<int, char> > nextNodes;
};


bool ValidWord(string&      word,
               int          crtNode,
               vector<Nod>& automat)
{

    // primul e indexul caracterului, al doilea e nodul
    queue<pair<int, int> > indexQueue;
    map<pair<int, int>, bool> beenThere;

    indexQueue.push(make_pair(0, crtNode));
    beenThere[make_pair(0, crtNode)] = true;

    while (!indexQueue.empty())
    {
        pair<int, int> cerElem = indexQueue.front();
        indexQueue.pop();

        int strIx = cerElem.first;
        int nod = cerElem.second;

        if (strIx >= word.size())
        {
            if (automat[nod].ending)
                return true;
        }
        else
        {
            char c = word[strIx];
            for (int i = 0; i < automat[nod].links[c].size(); i++)
            {
                pair<int, int> newPair = make_pair(strIx + 1, automat[nod].links[c][i]);
                if (beenThere.find(newPair) == beenThere.end())
                {
                    beenThere[newPair] = true;
                    indexQueue.push(newPair);
                }
            }
        }
    }

    return false;
}

int main()
{
    ifstream fin("nfa.in");
    ofstream fout("nfa.out");
    vector<Nod> automat;


    int n, m, nf;
    int q0;
    fin >> n >> m >> nf;
    fin >> q0;
    q0--;
    automat.resize(n);

    automat[q0].start = true;

    for (int i = 0; i < nf; i++)
    {
        int fn;
        fin >> fn;
        fn--;
        automat[fn].ending = true;
    }

    for (int i = 0; i < m; i++)
    {
        int q1, q2;
        char c;
        fin >> q1 >> q2 >> c;
        q1--;
        q2--;
        if (automat[q1].links.find(c) == automat[q1].links.end())
            automat[q1].links[c] = vector<int>();
        automat[q1].links[c].push_back(q2);
        automat[q1].nextNodes.push_back(make_pair(q2, c));
    }

    int nrW;
    fin >> nrW;

    for (int i = 0; i < nrW; i++)
    {
        string crtWord;
        fin >> crtWord;
        fout << ValidWord(crtWord, q0, automat) << endl;
    }

    fout.close();
    fin.close();

    return 0;
}