Cod sursa(job #100766)

Utilizator scapryConstantin Berzan scapry Data 12 noiembrie 2007 18:20:50
Problema Abc2 Scor 0
Compilator cpp Status done
Runda Happy Coding 2007 Marime 2.14 kb
#include <cstdio>
#include <cstring>
#include <cassert>

enum { maxlen = 10000002, maxwordlen = 20 };

int wordlen;
int len;
char str[maxlen];
int ans;

int news;

struct item
{
	item *t[9];

	item()
	{
		memset(t, 0, sizeof(t));
	}
} root;

#define printf(...) ;

inline int translate(const char *s)
/*
 * a_ = aa
 * b_ = ba
 * c_ = ca
 */
{
	assert(*s == 'a' || *s == 'b' || *s == 'c');

	int ret = (*s - 'a') * 4;

	s++;
	assert(*s == 0 || *s == 'a' || *s == 'b' || *s == 'c');
	if(*s != 0)
		ret += (*s - 'a');

	printf("translated [%.2s] into %d\n", s - 1, ret);
	return ret;
}

void add(item *pos, const char *s)
{
	int type;
	item **p;

	while(true)
	{
		printf("add [%.22s] at %p\n", s, pos);

		type = translate(s);
		p = &(pos->t[type]);

		if(*p == 0)
		{
			*p = new item;
			news++;
		}

		pos = *p;

		s += 2;

		if(*(s - 1) == 0 || *s == 0)
			break;
	}
}

void search(const item *pos, const char *s)
{
	int i, type;

	if(wordlen % 2)
	{
		printf("odd\n");

		for(i = 0; pos != 0 && i + 1 < wordlen; i += 2)
		{
			printf("%d) searching for [%.22s] at %p\n", i, s, pos);

			type = translate(s);
			pos = pos->t[type];
			s += 2;
		}

		if(pos)
		{
			printf("special) searching for [%.22s] at %p\n", s, pos);

			assert(i == wordlen - 1);

			type = translate(s);
			type /= 3;
			type *= 3;

			pos = pos->t[type];
		}
	}
	else
	{
		printf("even\n");

		for(i = 0; pos != 0 && i < wordlen; i += 2)
		{
			printf("%d) searching for [%.22s] at %p\n", i, s, pos);

			type = translate(s);
			pos = pos->t[type];
			s += 2;
		}
	}

	if(pos)
	{
		printf("found!\n");
		ans++;
	}
	else
		printf("not found\n");
}

void go()
{
	//for(char *start = str + len - wordlen; start >= str; start--)
	for(char *start = str; start + wordlen <= str + len; start++)
	{
		search(&root, start);
		printf("\n");
	}

#undef printf

	printf("ans eventually %d\n", ans);
}

int main()
{
	char word[maxwordlen + 2];

	freopen("abc2.in", "r", stdin);
	scanf("%s", str);
	len = strlen(str);
	while(scanf(" %s", word) != EOF)
	{
		add(&root, word);
		//printf("\n");
	}
	wordlen = strlen(word);

	printf("%d news\n", news);

	go();
	
	freopen("abc2.out", "w", stdout);
	printf("%d\n", ans);
	return 0;
}