Cod sursa(job #98198)

Utilizator bogdan2412Bogdan-Cristian Tataroiu bogdan2412 Data 10 noiembrie 2007 10:56:49
Problema Abc2 Scor 0
Compilator cpp Status done
Runda Happy Coding 2007 Marime 1.92 kb
#include <cstdio>
#include <vector>
#include <string>

using namespace std;

#define MAXL 10000005
#define MAXN (50005*21)
#define SIGMA 3

int N;
char s[MAXL];
char tmp[32];

vector<string> v;
vector<int> stareCur;

vector< vector<int> > Tr, DFA;
vector< int > niv, p, term;

int NR;

inline int add( const string &s, int ID )
{
	int i = 0, stare = 0;
	for (; s[i]; i++)
	{
		if (Tr[stare][ s[i] - 'a' ] == -1)
		{
			Tr[stare][ s[i] - 'a' ] = ++NR;

			Tr.push_back( vector<int>(SIGMA, -1) );
			niv.push_back( niv[stare] + 1 );
			p.push_back( stare );
			term.push_back(0);

			stare = NR;
		}
		else
			stare = Tr[stare][ s[i] - 'a' ];
	}
	return stare;
}

int main()
{
	freopen("abc2.in", "rt", stdin);
	freopen("abc2.out", "wt", stdout);
	int i;
	fgets(s, MAXL, stdin);

	v.clear();
	for (N = 0; fgets(tmp, 32, stdin); )
	{
		N++;
		
		int k;
		for (k = 0; 'a' <= tmp[k] && tmp[k] <= 'z'; k++);
		tmp[k] = 0;

		if (k == 0) continue;
		v.push_back( tmp );
	}
	stareCur.resize( v.size(), 0 );

	//init
	Tr.reserve(N);
	NR = 0; niv.push_back(0); p.push_back(-1); term.push_back(0);
	Tr.push_back( vector<int>(SIGMA, -1) );

	//make trie
	for (i = 0; i < N; i++)
		term[ add( v[i], i ) ] = 1;

	//make DFA
	DFA.resize( Tr.size(), vector<int>(SIGMA, 0) );
	int wlen = (int)v[0].size();
	for (i = 0; i < wlen; i++)
	{
		int j;
		for (j = 0; j < N; j++)
		{
			int k, stare, parent, aux, C = v[j][i] - 'a';
			stare = stareCur[j] = Tr[ stareCur[j] ][C];
			parent = p[stare];
			aux = DFA[ parent ][ C ];
			if (term[ DFA[parent][ C ] ])
				term[stare] = 1;

			DFA[parent][ C ] = stare;
			for (k = 0; k < SIGMA; k++)
				DFA[stare][k] = DFA[aux][k];
			if (niv[aux] == niv[parent])
				for (k = 0; k < SIGMA; k++)
					if (Tr[aux][k] != -1)
						DFA[stare][k] = Tr[aux][k];
		}
	}

	//get matchings
	int stare = 0, NR = 0;
	for (i = 0; s[i] != '\n'; i++)
	{
		stare = DFA[stare][ s[i] - 'a' ];
		if (term[stare])
			NR++;
	}

	printf("%d\n", NR);
	return 0;
}