Cod sursa(job #3233343)

Utilizator MirceaDonciuLicentaLicenta Mircea Donciu MirceaDonciuLicenta Data 2 iunie 2024 23:49:29
Problema Substr Scor 40
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.2 kb
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <string>
#include <vector>

using namespace std;

bool check(const string& text, int length, int K) {
    unordered_map<string, int> substrCount;
    for (int i = 0; i <= text.size() - length; ++i) {
        string substr = text.substr(i, length);
        substrCount[substr]++;
    }

    for (const auto& entry : substrCount) {
        if (entry.second >= K) {
            return true;
        }
    }
    return false;
}

int longestKRepeatedSubstring(const string& text, int K) {
    int left = 1, right = text.size();
    int result = 0;

    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (check(text, mid, K)) {
            result = mid;
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    return result;
}

int main() {
    ifstream infile("substr.in");
    ofstream outfile("substr.out");

    int N, K;
    infile >> N >> K;

    string text;
    infile >> text;

    int result = longestKRepeatedSubstring(text, K);
    outfile << result << endl;

    infile.close();
    outfile.close();

    return 0;
}