Cod sursa(job #98383)

Utilizator eferLiviu Ciortea efer Data 10 noiembrie 2007 13:00:06
Problema Abc2 Scor 0
Compilator cpp Status done
Runda Happy Coding 2007 Marime 2.39 kb
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <algorithm>
#include <vector>
#include <utility>
#include <string>
#include <iostream>
#include <ctime>
using namespace std;

#define REP(i, N) for (i = 0; i < (N); ++i)
#define REPV(i, a, b) for (i = (a); i <= (b); ++i)
#define REPD(i, N) for (i = (N)-1; i >= 0; --i)
#define REPVD(i, b, a) for (i = (b); i >= (a); --i)
#define CLR(a) memset(a, 0, sizeof(a))
#define MSET(a, v) memset(a, v, sizeof(a))
#define CPY(dest, source) memcpy(dest, source, sizeof(source))
#define PB push_back
#define SZ(a) (int)(a).size()
#define ALL(a) ((a).begin(), (a).end())
#define min(a, b) ((a) < (b) ? (a) : (b))

typedef vector<int> VI;
typedef pair<int, int> PII;
typedef __int64 LL;
typedef vector<string> VS;

int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79};

int MAXH = 1<<20;
int N, M;
char buff[32];
vector<LL> hash[1<<20];

const int MAXS = 10000020;
char str[MAXS];

int hashcode(LL num) {
	unsigned int h = 0;
	int i;


	REP(i, M) {
		h = ((h << 5) + h) + (num & 3);
		num >>= 2;
	}

	return h % MAXH;
	//return num % MAXH;
}

int find(LL num) {
	int ind = hashcode(num), i;
	REP(i, SZ(hash[ind])) if (hash[ind][i] == num) return 1;
	return 0;
}

void puthash(LL num) {
	int ind = hashcode(num);
	if (!find(num)) hash[ind].PB(num);
}

LL encode() {
	M = strlen(buff);
	LL res = 0;
	int i;
	REP(i, M) res = (res << 2) | (buff[i] - 'a');

	return res;
}

void parsewords() {
	scanf("%s", str);
	while (scanf("%s", buff) == 1) {
		puthash(encode());
		N++;
	}
}

int main() {
	//time_t start = clock();
	freopen("abc2.in", "rt", stdin);
	freopen("abc2.out", "wt", stdout);

	random_shuffle(primes, primes + (sizeof(primes) / sizeof(primes[0])));

	parsewords();

	int S = strlen(str);
	if (S < M) {
		printf("0\n");
		return 0;
	}

	int i;
	//REP(i, MAXH) if (SZ(hash[i]) > 5) fprintf(stderr, "%d ", SZ(hash[i]));

	LL mask = 0;
	REP(i, M) mask = (mask << 2) | 3;

	strncpy(buff, str, M);
	LL curr = encode();

	//fprintf(stderr, "%I64d\n", curr);

	int res = find(curr);

	REPV(i, M, S-1) {
		curr = (curr << 2) | (str[i] - 'a');
		curr &= mask;

		//fprintf(stderr, "%I64d\n", curr);

		res += find(curr);
	}

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

	//fprintf(stderr, "%lf\n", 1.0 * (clock() - start) / CLK_TCK);

	return 0;
}