Cod sursa(job #1069085)

Utilizator R.A.RFMI Romila Remus Arthur R.A.R Data 29 decembrie 2013 13:39:43
Problema Substr Scor 0
Compilator cpp Status done
Runda Teme Pregatire ACM Unibuc 2013 Marime 1.1 kb
#include <fstream>
#include <cstring>
using namespace std;

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

const int NMAX = 16384;
const int BASE = 137;
const int DISP = 8666017;
string data;

int hashMap[DISP];

int N, K;

bool isMatching(int value){

    unsigned int hashKey = 0, basePower = 1, i, v, result = 0; //dispersion by overflow

    for(i = 1, hashKey = data[0]; i < value; i++){
        hashKey = (hashKey*BASE + data[i]) % DISP;
        basePower = (basePower * BASE) % DISP;
    }

    hashMap[hashKey] = 1;

    for(i = value; i < N; i++){
        hashKey = ((hashKey - data[i-value] * basePower) * BASE + data[i]) % DISP;

        v = ++hashMap[hashKey];
        if(v > result)
            result = v;
    }

    memset(hashMap, 0, sizeof(hashMap));

    if(result >= K)
        return true;
    else return false;
}

int main()
{
    in >> N >> K >> data;

    int step = 1, result ;

    while(step <= N) step<<=1;

    for(result = 0; step; step>>=1){

        if(result + step <= N && isMatching(result+step))
            result+=step;
    }

    out << result << '\n';
    return 0;
}