Cod sursa(job #3130513)

Utilizator ecaterinaEcaterina Stefanescu ecaterina Data 17 mai 2023 21:47:33
Problema Substr Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.39 kb
#include <iostream>
#include <stdio.h>
#include <vector>
#include <cstring>
#include <algorithm>

using namespace std;

#define NMAX 16384
#define HASHBASE 128
#define HASHSIZE1 1000000009

int n, k;
char sir[NMAX];

long long int hash1[NMAX];

void myqsort1(long long int begin, long long int end) {
    long long int b, e, pivot, aux;
    
    b = begin;
    e = end;
    pivot = hash1[(e+b)/2];
    
    while (hash1[b]<pivot) {
        b++;
    }
    while (hash1[e]>pivot) {
        e--;
    }
    while (b<e) {
        aux = hash1[b];
        hash1[b] = hash1[e];
        hash1[e] = aux;
        do {
            b++;
        } while (hash1[b]<pivot);
        do {
            e--;
        } while (hash1[e]>pivot);
    }
    if (begin < e) {
        myqsort1(begin, e);
    }
    if (e+1 < end) {
        myqsort1(e+1, end);
    }
}

int verif(int lung) {
    long long int pow1, h1;
    int i, j, ok;
    
    pow1 = 1;
    for (i=0; i<lung-1; i++) {
        pow1 = (pow1*HASHBASE)%HASHSIZE1;
    }
    
    h1 = 0;
    for (i=0; i<lung; i++) {
        h1 = (h1*HASHBASE + sir[i])%HASHSIZE1;
    }
    hash1[0] = h1;
    
    for (i=lung; i<n; i++) {
        h1 = (h1-sir[i-lung]*pow1)%HASHSIZE1;
        if (h1<0) {
            h1+=HASHSIZE1;
        }
        h1 = (h1*HASHBASE + sir[i])%HASHSIZE1;
        
        hash1[i-lung+1] = h1;
    }
    
    myqsort1(0, n-lung);
    i=0;
    ok = 0;
    while (i<n-lung+1 && ok==0) {
        j=1;
        while (hash1[i]==hash1[i+j] && i+j<n-lung+1) {
            j++;
        }
        i += j;
        if (j>=k) {
            ok = 1;
        }
    }
    
    return ok;
}

int main() {
    FILE *fin, *fout;
    fin = fopen("substr.in", "r");
    fout = fopen("substr.out", "w");
    
    int st, dr, mijl, i, rez;
    char ch;
    
    fscanf(fin, "%d%d", &n, &k);
    
    ch = fgetc(fin);
    while (!((ch>='0' && ch<='9') || (ch>='a' && ch<='z') || (ch>='A' && ch<='Z'))) {
        ch = fgetc(fin);
    }
    i=0;
    while ((ch>='0' && ch<='9') || (ch>='a' && ch<='z') || (ch>='A' && ch<='Z')) {
        sir[i] = ch;
        i++;
        ch = fgetc(fin);
    }
    
    
    verif(2);
    
    
    st = 0;
    dr = n;
    while (dr-st>1) {
        mijl = (st+dr)/2;
        rez = verif(mijl);
        if (rez==0) {
            dr = mijl;
        } else {
            st = mijl;
        }
    }
    
    fprintf(fout, "%d", st);
    
    
    fclose(fin);
    fclose(fout);
    return 0;
}