Cod sursa(job #2159059)

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

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

typedef long long LL;

const LL MOD1 = 1000003;
const LL MOD2 = 1000033;
const LL B = 77;
int n, k, sol = 1;
LL p[17000], p2[17000];
LL h[17000], h2[17000];
char s[17000];

unordered_map<LL, int> Map;
unordered_map<LL, int> Map2;

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

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

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

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

    for (int i = x + 1; i <= n; ++i) {
        LL sh = ((h[i] - (h[i - x] * p[x]) % MOD1) + MOD1) % MOD1;
        LL sh2 = ((h2[i] - (h2[i - x] * p2[x]) % MOD2) + MOD2) % MOD2;
        Map[sh]++;
        Map2[sh2]++;
        if (Map[sh] >= k && Map2[sh2] >= 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;
}