Cod sursa(job #98274)

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

using namespace std;

#define MAXL 10000005
#define MAXCuv 50005
#define MAXN (MAXCuv*12)
#define SIGMA 3

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

int stareCur[MAXCuv];
char v[MAXCuv][21];

int Tr[MAXN][SIGMA], niv[MAXN], p[MAXN], term[MAXN], DFA[MAXN][SIGMA], NR;

inline int add( char s[], int ID )
{
	int i = 0, j, stare = 0;
	for (; s[i]; i++)
	{
		if (Tr[stare][ s[i] - 'a' ] == -1)
		{
			Tr[stare][ s[i] - 'a' ] = ++NR;
			for (j = 0; j < SIGMA; j++)
				Tr[NR][j] = -1;
			niv[NR] = niv[stare] + 1;
			p[NR] = stare;
			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);

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

		if (k == 0)
			continue;

		N++;
	}

	//init
	NR = 0; p[0] = -1;
	memset(term, 0, sizeof(term));
	for (i = 0; i < SIGMA; i++)
	{
		Tr[0][i] = -1;
		DFA[0][i] = 0;
	}

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

	//make DFA
	int wlen = strlen( v[0] );
	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;
			memcpy( DFA[stare], DFA[aux], sizeof( DFA[stare] ) );
			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;
}