Cod sursa(job #2979859)

Utilizator KarinaDKarina Dumitrescu KarinaD Data 16 februarie 2023 00:07:46
Problema Substr Scor 30
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <unordered_map>

using namespace std;

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

const int N = 1e6;
const int MOD = 1e9 + 7;
int v[N];

long long power ( int e ){
    
    long long p = 1, x = 29;
    
    while ( e > 0 ) {
        if ( e % 2 == 1 )
            p = ( p * x ) % MOD;
        
        x = ( x * x ) % MOD;
        e = e / 2;
    }
    
    return p;
}

int solve ( int k, int n ){
    
    unordered_map <long long, int> f;
    
    long long p = power ( k - 1 );
    
    int hash = 0;
    
    for ( int i = 0; i < k; i++ )
        hash = ( long long )( hash * 29 + v[i] ) % MOD;
    
    f[hash]++;
    
    int ans = 1;
    
    for ( int i = k; i < n; i++ ) {
        
        hash = ( long long )( 29 * ( hash - v[i - k] * p ) + v[i] ) % MOD;
        
        if ( hash < 0 )
            hash = hash + MOD;
        
        f[hash]++;
   
        ans = max ( ans, f[hash] );
    }
        
    return ans;
}

int main () {
    
    int n, k, i;
    string s;
    
    fin >> n >> k;
    fin >> s;
    
    for ( i = 0; i < s.size(); i++ )
        v[i] = s[i] - 'a' + 1;
    
    int st = 0, dr = n + 1;
    
    while ( dr - st > 1 ) {
        
        int mij = ( st + dr ) / 2;
        
        if ( solve( mij, n ) >= k )
            st = mij;
        else
            dr = mij;
    }

    fout << st;
    
    return 0;
}