Cod sursa(job #2027920)

Utilizator vladdy47Bucur Vlad Andrei vladdy47 Data 26 septembrie 2017 21:14:47
Problema Abc2 Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2 kb
# include <bits/stdc++.h>
# define MOD1 666013
# define MOD2 2017
# define ll long long

using namespace std;

const int len_max = 26 + 5, text_max = 1e7 + 5;

vector <int> Hash[MOD1];

char text[text_max], s[len_max];
int n, m, pw[len_max], pw2[len_max];
ll ans;

void powers()
{
    pw[0] = pw2[0] = 1;
    for (int i = 1; i <= len_max; ++i){
        pw[i] = (pw[i - 1] * 27) % MOD1;
        pw2[i] = (pw2[i - 1] * 27) % MOD2;
    }
}

ll Search(int key, int val)
{
    for (auto &it: Hash[key])
        if (it == val) return 1;

    return 0;
}

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

    gets(text + 1), n = strlen(text + 1);
    powers();
    gets(s + 1), m = strlen(s + 1);
    do
    {   int hash_a1 = 0, hash_a2 = 0;


        for (int i = 1; i <= m; ++i)
            hash_a1 += (s[i] * pw[m - i + 1]) % MOD1, hash_a2 += (s[i] * pw2[m - i + 1]) % MOD2;
            hash_a1 %= MOD1, hash_a2 %= MOD2;

        Hash[hash_a1].push_back(hash_a2);
        gets(s + 1), m = strlen(s + 1);
    }
    while (!feof(stdin));

    int hash_b1 = 0, hash_b2 = 0;

    for (int i = 1; i <= n; ++i)
    {
        if (i <= m) {
            hash_b1 += (pw[m - i + 1] * text[i]) % MOD1, hash_b1 %= MOD1;
            hash_b2 += (pw2[m - i + 1] * text[i]) % MOD2, hash_b2 %= MOD2;
            if (i < m) continue;
        }

        if (i > m) {
            hash_b1 -= (pw[m] * text[i - m]) % MOD1;
            hash_b1 %= MOD1, hash_b1 += MOD1, hash_b1 %= MOD1;

            hash_b2 -= (pw2[m] * text[i - m]) % MOD2;
            hash_b2 %= MOD2, hash_b2 += MOD2, hash_b2 %= MOD2;

            hash_b1 *= pw[1] , hash_b1 %= MOD1;
            hash_b2 *= pw2[1], hash_b2 %= MOD2;

            hash_b1 += (text[i] * pw[1]) % MOD1, hash_b2 += (text[i] * pw2[1]) % MOD2;
            hash_b1 %= MOD1, hash_b2 %= MOD2;

        }

        ans += 1LL * Search(hash_b1, hash_b2);
    }

    printf("%lld\n", ans);

    return 0;
}