Cod sursa(job #2159086)

Utilizator savigunFeleaga Dragos-George savigun Data 10 martie 2018 18:50:54
Problema Substr Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.18 kb
#include <iostream>
#include <fstream>
#include <unordered_map>
using namespace std;

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

typedef unsigned long long LL;

const int MAXLL = 1LL << 64;
const LL B = 77;
int n, k, sol = 1;
LL p[17000], h[17000];
char s[17000];

unordered_map<LL, int> Map;

void preprocess() {
    int ioc;
    for (int i = 1; i <= n; ++i) {
        ioc = s[i] - '0' + 1;
        h[i] = h[i-1] * B + ioc;
    }

    p[0] = 1;
    for (int i = 1; i <= n; ++i) {
        p[i] = p[i - 1] * B;
    }
}

bool ok(int x) {
    Map.clear();

    Map[h[x]]++;
    if (Map[h[x]] >= k) return true;

    for (int i = x + 1; i <= n; ++i) {
        LL sh = (h[i] - (h[i - x] * p[x])) + MAXLL;
        Map[sh]++;
        if (Map[sh] >= k) return true;
    }

    return false;
}

int main()
{
    in >> n >> k;
    in >> (s + 1);

    preprocess();

    int left = 1;
    int right = n;

    while (left <= right) {
        int mid = (left + right) / 2;
        if (ok(mid)) {
            sol = mid;
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    out << sol;

    return 0;
}