Cod sursa(job #1402107)

Utilizator addy01adrian dumitrache addy01 Data 26 martie 2015 12:33:12
Problema Substr Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.62 kb
#include <iostream>
#include <fstream>
#include <tr1/unordered_map>

using namespace std;

ifstream in("substr.in");
ofstream out("substr.out");

const int maxn  =  16384 + 10;
const int MOD1  =  37;
const int MOD2  =  71;
const int power1 =  137;
const int power2 =  41;

typedef unsigned long long ULL;

tr1 :: unordered_map < pair<ULL,ULL> , int> Q;

int N,K;
ULL P1[maxn];
ULL P2[maxn];
char S[maxn];

void preproc(){
    int i;
    P1[0] = 1;
    P2[0] = 1;
    for (i=1;i<=N;i++){
        P1[i] = ( P1[i-1] * power1 ) % MOD1;
        P2[i] = ( P2[i-1] * power2 ) % MOD2;
    }
}

bool ok(int len){
    int Ans = 1, i ;
    int hash1 = 0,hash2 = 0;
    for ( i = 0 ; i < len ; i++ ){
        hash1 = ( hash1 * power1 + S[i] ) % MOD1;
        hash2 = ( hash2 * power2 + S[i] ) % MOD2;
    }

    Q[make_pair(hash1,hash2)]++;

    for( i = len ; i <= N ; i++ ){
        hash1 = ( hash1 - S[i - len] * P1[len - 1] + MOD1 ) % MOD1;
        hash2 = ( hash2 - S[i - len] * P2[len - 1] + MOD2 ) % MOD2;
        hash1 = ( hash1 * power1 + S[i] + MOD1 ) % MOD1;
        hash2 = ( hash2 * power2 + S[i] + MOD2 ) % MOD2;

       Q[make_pair(hash1,hash2)]++;

        if( Ans > Q[make_pair(hash1,hash2)] )
            Ans = Q[make_pair(hash1,hash2)];
    }

    return (Ans >= K) ;
}

int bsearch()
{
    preproc();

    int i=0,step;
    for ( step = 1; step < N; step *= 2 );
    for ( ; step; step /= 2 )
        if( step + i <= N && ok( i + step ) )
            i += step;
    return i;
}

int main()
{
    int i;
    in>>N>>K;
    in>>S;

    cout<<bsearch();

    return 0;
}