Cod sursa(job #1498513)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 8 octombrie 2015 18:12:01
Problema Abc2 Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.6 kb
#include<fstream>
#include<string>
#include<vector>

using namespace std;

ifstream fin( "abc2.in" ); ofstream fout( "abc2.out" );

const int key = 1922923;
unsigned int p3[ 21 ];
vector< unsigned int > h[ key ];
string shp; string::iterator t;
string s, cuv;

bool hash_search( unsigned int x ) {
    unsigned int k = x % key;
    for( vector< unsigned int >::iterator it = h[ k ].begin(); it != h[ k ].end(); ++ it ) {
        if ( *it == x ) {
            return 1;
        }
    }
    return 0;
}
bool get_string( string &u ) {
    u.clear();
    while ( t != shp.end() && (*t < 'a' || *t > 'c') ) {
        ++ t;
    }
    while ( t != shp.end() && (*t >= 'a' && *t <= 'z') ) {
        u.push_back( *t );
        ++ t;
    }
    return ( u.size() > 0 );
}
int main() {
    int l;
    getline( fin, shp, (char)0 );
    t = shp.begin();
    get_string( s );

    p3[ 0 ] = 1;
    for( int i = 1; i < 20; ++ i ) {
        p3[ i ] = p3[ i - 1 ] * 3;
    }

    while ( get_string( cuv ) ) {
        unsigned int x = 0;
        for( int i = 0; i < ( int )cuv.size(); ++ i ) {
            x = (x * 3 + cuv[ i ] - 'a');
        }
        if ( hash_search( x ) == 0 ) {
            h[ x % key ].push_back( x );
        }
        l = ( int )cuv.size();
    }

    unsigned int x = 0;
    for( int i = 0; i < l - 1; ++ i ) {
        x = (x * 3 + s[ i ] - 'a');
    }
    int ans = 0;
    for( int i = l - 1; i < ( int )s.size(); ++ i ) {
        x = (x * 3 + s[ i ] - 'a');
        ans += hash_search( x );
        x -= (p3[ l - 1 ] * (s[ i - l + 1 ] - 'a') );
    }
    fout << ans << "\n";
    fin.close();
    fout.close();
    return 0;
}