Cod sursa(job #106747)

Utilizator octavOctavian Voicu octav Data 18 noiembrie 2007 22:15:23
Problema Abc2 Scor 0
Compilator cpp Status done
Runda Happy Coding 2007 Marime 1.46 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXTEXT 10000000
#define MAXLEN 20
#define MAXWORDS 50000
#define HASHSIZE (1 << 24)

typedef unsigned long long CODE;
CODE hashcode[HASHSIZE];
CODE hashmask[HASHSIZE];
CODE maxmask;

char text[MAXTEXT + 1];

int hash_code(CODE code, CODE mask) {
	return (code & 0xffffff) ^ ((code >> 25) & 0xffffff) ^ (mask & 0xffffff);
}

void hash_add(char *word) {
	CODE code, mask;
	char *p;
	int h;

	code = 0;
	mask = 0;
	for(p = word; *p; p++) {
		code <<= 2;
		code |= *p - 'a';
		mask <<= 2;
		mask |= 3;
	}
	if(maxmask < mask) maxmask = mask;

	h = hash_code(code, mask);
	while(hashmask[h] && (hashcode[h] != code || hashmask[h] != mask)) h = (h + 1) & (HASHSIZE - 1);
	if(hashmask[h]) return;
	hashcode[h] = code;
	hashmask[h] = mask;
}

int hash_find(CODE code, CODE mask) {
	int h;
	code &= mask;
	h = hash_code(code, mask);
	while(hashmask[h] && (hashcode[h] != code || hashmask[h] != mask)) h = (h + 1) & (HASHSIZE - 1);
	return hashmask[h] ? 1 : 0;
}

int main() {
	CODE code, mask;
	char word[MAXLEN + 1], *p;
	int count;

	freopen("abc2.in", "rt", stdin);
	freopen("abc2.out", "wt", stdout);

	gets(text);

	while(gets(word)) hash_add(word);

	count = 0;
	code = 0;
	for(p = text; *p; p++) {
		code <<= 2;
		code |= *p - 'a';
		for(mask = maxmask; mask; mask >>= 2) {
			if(hash_find(code, mask)) count++;
		}
	}

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

	return 0;
}