Cod sursa(job #3209688)

Utilizator alex_0747Gheorghica Alexandru alex_0747 Data 3 martie 2024 12:02:46
Problema Substr Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.63 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#define P 123457
#define Q 777013
using namespace std;

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

string s;
int n, k;
vector <pair<int, int> > v;

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

bool Check(int L)
{
    int i, x1, x2, p1, p2, l;
    v.clear();
    x1 = x2 = 0;
    p1 = p2 = 1;
    for (i = 1; i < L; i++)
    {
        p1 = (p1 * 62) % P;
        p2 = (p2 * 62) % Q;
    }
    for (i = 0; i < L; i++)
    {
        x1 = (x1 * 62 + Cod(s[i])) % P;
        x2 = (x2 * 62 + Cod(s[i])) % Q;
    }
    v.push_back({ x1, x2 });
    for (; i < n; i++)
    {
        x1 = (x1 - Cod(s[i - L]) * p1 % P + P) % P;
        x2 = (x2 - Cod(s[i - L]) * p2 % Q + Q) % Q;
        x1 = (x1 * 62 + Cod(s[i])) % P;
        x2 = (x2 * 62 + Cod(s[i])) % Q;
        v.push_back({ x1, x2 });
    }
    sort(v.begin(), v.end());
    l = 1;
    for (i = 1; i < n - L + 1; i++)
        if (v[i] == v[i - 1])
        {
            l++;
            if (l == k) return 1;
        }
        else l = 1;
    return 0;
}

void Search()
{
    int st, dr, mij, l;
    st = 1; dr = n; l = 1;
    while (st <= dr)
    {
        mij = (st + dr) / 2;
        if (Check(mij))
        {
            l = mij;
            st = mij + 1;
        }
        else
            dr = mij - 1;
    }
    fout << l << "\n";
}

int main()
{
    fin >> n >> k;
    fin >> s;
    Search();
    fout.close();
    return 0;
}