Cod sursa(job #2159046)

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

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

typedef long long LL;

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

inline int intof(char c) {
    return (c - '0' + 1);
}

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

bool ok(int x) {
    unordered_map<LL, int> Map;
    unordered_map<LL, int> Map2;
    Map[h[x]]++;
    Map2[h2[x]]++;
    if (Map[h[x]] >= k && Map2[h2[x]] >= k) return true;

    LL p = 1, p2 = 1;
    for (int i = 1; i <= x; ++i) {
        p = (p * B) % MOD1;
        p2 = (p2 * B) % MOD2;
    }

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