Cod sursa(job #101847)

Utilizator silviugSilviu-Ionut Ganceanu silviug Data 13 noiembrie 2007 21:20:30
Problema Abc2 Scor 0
Compilator cpp Status done
Runda Happy Coding 2007 Marime 2.24 kb
#include <algorithm>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <sstream>
#include <vector>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <cstring>

using namespace std;

#define REP(i, N) for (int i = 0; i < (int)(N); ++i)
#define FOR(i, N, M) for (int i = (int)(N); i <= (int)(M); ++i)
#define FORD(i, N, M) for (int i = (int)(N); i >= (int)(M); --i)
#define FORI(it, x) for (__typeof((x).begin()) it = (x).begin(); it != (x).end(); ++it)
#define TIP(x) (cerr << #x << " = " << (x) << endl)
#define sz size()
#define pb push_back
#define mp make_pair
#define pf first
#define ps second
#define INF 1000000000
#define ALL(x) (x).begin(), (x).end()
#define CLEAR(X) (memset(X, 0, sizeof(X)))
typedef vector<int> VI;
typedef vector<string> VS;
typedef long long LL;

const int MAX_LEN = 10000010;
const uint HASH_SIZE = 1 << 20;
const uint prime = 101;

int N;
char cuv[64];
char text[MAX_LEN];
bool viz[HASH_SIZE];

inline uint fun(uint val) {
    return val & (HASH_SIZE - 1);
}

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

    fgets(text, MAX_LEN, stdin);
    while (true) {
        CLEAR(cuv);
        fgets(cuv, 64, stdin);
        int len = strlen(cuv);
        if (cuv[len - 1] == '\n') {
            cuv[len - 1] = 0;
            --len;
        }
        if (len == 0) {
            break;
        }
        N = len;
        uint hash = 0;
        for (int i = 0; i < len; ++i) {
            hash = hash * prime + cuv[i];
        }
        viz[fun(hash)] = 1;
    }

    uint crt_hash = 0, primeN = 1;
    for (int i = 0; i < N; ++i)
        primeN *= prime;
    primeN = fun(primeN);

    int i, sol = 0;
    for (i = 0; i < N; ++i) {
        crt_hash = crt_hash * prime + text[i];
    }
    crt_hash = fun(crt_hash);
    for (; text[i] != '\n' && text[i] != '\0'; ++i) {
    //    TIP(crt_hash);
        sol += (int) viz[crt_hash];
        crt_hash *= prime;
        crt_hash = crt_hash + (HASH_SIZE - fun(primeN * text[i - N]));
        while (crt_hash < 0) crt_hash += HASH_SIZE;
        crt_hash += text[i];
        crt_hash = fun(crt_hash);
    }
    sol += (int) viz[crt_hash];
    printf("%d\n", sol);
	return 0;
}