Pagini recente » Cod sursa (job #793377) | Cod sursa (job #773675) | Cod sursa (job #3296387) | Cod sursa (job #1249893) | Cod sursa (job #2588223)
#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 letterIndex,
int crtNode,
vector<Nod>& automat)
{
// inainte sa realizez ca se poate face si in complexitate polinomiala
/*
bool result = false;
if (letterIndex >= word.size())
{
if (automat[crtNode].ending)
return true;
return false;
}
char c = word[letterIndex];
if (automat[crtNode].links.find(c) != automat[crtNode].links.end())
{
for (int i = 0; i < automat[crtNode].links[c].size(); i++)
result = result || ValidWord(word,
letterIndex + 1,
automat[crtNode].links[c][i],
automat);
}
*/
// primul e indexul caracterului, al doilea e nodul
queue<pair<int, int> > indexQueue;
map<pair<int, int>, bool> beenThere;
bool result = false;
indexQueue.push(make_pair(0, crtNode));
beenThere[make_pair(0, crtNode)] = true;
while (!(indexQueue.empty() || result))
{
pair<int, int> cerElem = indexQueue.front();
indexQueue.pop();
int strIx = cerElem.first;
int nod = cerElem.second;
if (strIx >= word.size())
{
if (automat[nod].ending)
result = 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 result;
}
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);
int* finals = new int[nf];
for (int i = 0; i < nf; i++)
fin >> finals[i];
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));
}
automat[q0].start = true;
for (int i = 0; i < nf; i++)
automat[finals[i] - 1].ending = true;
delete[] finals;
int nrW;
fin >> nrW;
for (int i = 0; i < nrW; i++)
{
string crtWord;
fin >> crtWord;
fout << ValidWord(crtWord, 0, q0, automat) << endl;
}
fout.close();
fin.close();
return 0;
}