Cod sursa(job #2697541)

Utilizator As932Stanciu Andreea As932 Data 18 ianuarie 2021 21:26:31
Problema Substr Scor 70
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.41 kb
#include <fstream>
#include <string>
#include <unordered_map>

using namespace std;

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

typedef long long ll;

const int nmax = 16400;
const int base = 97;
const ll mod = 1e9 + 7;

int n, k;
string s;
ll pw[nmax], h[nmax];

void read(){
    cin >> n >> k;
    cin >> s;
}

int cif(char ch){
    if(ch >= 'a' && ch <= 'z')
        return (ch - 'a');
    if(ch >= 'A' && ch <= 'Z')
        return (ch - 'A' + 26);
    return (ch - '0' + 52);
}

void init(){
    pw[0] = 1;

    for(int i = 1; i <= n; i++)
        pw[i] = (1LL * pw[i - 1] * base) % mod;

    for(int i = 1; i <= n; i++)
        h[i] = (1LL * h[i - 1] * base + cif(s[i - 1])) % mod;
}

bool checks(int len){
    unordered_map <ll, int> mp;

    for(int i = 1; i <= n - len + 1; i++){
        ll nr = h[i + len - 1] - 1LL * h[i - 1] * pw[len];

        if(nr < 0)
            nr += mod;

        nr %= mod;

        mp[nr]++;
    }

    for(auto it : mp)
        if(it.second >= k)
            return true;

    return false;
}

void findAns(){
    init();

    int l = 0, r = n / k, mid, ans = 0;

    while(l <= r){
        mid = (l + r) / 2;

        if(checks(mid)){
            ans = mid;
            l = mid + 1;
        } else
            r = mid - 1;
    }

    cout << ans;
}

int main()
{
    read();
    findAns();

    return 0;
}