Cod sursa(job #100017)

Utilizator victorsbVictor Rusu victorsb Data 11 noiembrie 2007 19:54:18
Problema Abc2 Scor 0
Compilator cpp Status done
Runda Happy Coding 2007 Marime 1.68 kb
#include <cstdio>
#include <cstring>

#define Nmax 10000015
#define Mmax 50015
#define Lmax 22
#define Smax 1024 * 1024

int n, m, l, ct;
char sir[Nmax];
char cuv[Mmax][Lmax];
int trie[Smax][3];
int atm[Smax][3];
int c[Smax];
int t[Smax];
char last[Smax];
char ok[Smax];

void citire()
{
	fgets(sir, Nmax, stdin);
    while(!feof(stdin))
	{
		fgets(cuv[m + 1], Lmax, stdin);
		if ('a' <= cuv[m + 1][0] && cuv[m + 1][0] <= 'c') ++m;
	}
}

void insert(int ind)
{
	int i, pos = 0;

	for (i = 0; i < l; ++i)
	{
		if (!trie[pos][(int)cuv[ind][i]])
			trie[pos][(int)cuv[ind][i]] = ++ct;
		
		pos = trie[pos][(int)cuv[ind][i]];
	}
    ok[pos] = 1;
}

void BF()
{
	int st = 0, dr = 1, nod, i, bunic;

    while (st < dr)
	{
		nod = c[++st];

		for (i = 0; i < 3; ++i)
			if (nod)
			{
				bunic = atm[t[nod]][(int)last[nod]];

				if (trie[bunic][i]) atm[nod][i] = trie[bunic][i];
				else atm[nod][i] = atm[bunic][i];
			}

        atm[t[nod]][(int)last[nod]] = nod;

		for (i = 0; i < 3; ++i)
			if (trie[nod][i])
			{
				c[++dr] = trie[nod][i];
				t[trie[nod][i]] = nod;
				last[trie[nod][i]] = i;
			}
	}
}

void solve()
{
	int i, j, pos = 0, sol = 0;

    l = strlen(cuv[1]);
	while (l > 0 && !('a' <= cuv[1][l - 1] && cuv[1][l - 1] <= 'c')) --l;
    for (i = 1; i <= m; ++i)
		for (j = 0; j < l; ++j)
			cuv[i][j] -= 'a';

	for (i = 1; i <= m; ++i)
		insert(i);
	BF();

	n = strlen(sir);
	while (n > 0 && !('a' <= sir[n - 1] && sir[n - 1] <= 'c')) --n;
	for (i = 0; i < n; ++i)
		sir[i] -= 'a';

    for (i = 0; i < n; ++i)
	{
		pos = atm[pos][(int)sir[i]];
		sol += ok[pos];
	}

	printf("%d\n", sol);
}

int main()
{
	freopen("abc2.in", "r", stdin);
	freopen("abc2.out", "w", stdout);

	citire();
	solve();

	return 0;
}