Cod sursa(job #1810674)

Utilizator Athena99Anghel Anca Athena99 Data 20 noiembrie 2016 14:19:00
Problema Substr Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.26 kb
#include <fstream>
#include <string>

using namespace std;

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

const int sigma= 26+26+10;
const int mod= 982157;

int n, k;
int v1[mod], v2[mod];

string s;

int value( char x ) {
     if ( x>='0' && x<='9' ) {
          return x-'0';
     } else if ( x>='a' && x<='z' ) {
          return 10+x-'a';
     }
     return 10+26+x-'A';
}

bool check( int x ) {
     int p= 1;
     for ( int i= 1; i<=x-1; ++i, p= (p*sigma)%mod ) ;

     int h= 0;
     for ( int i= 1; i<=x; ++i ) {
          h= (h*sigma+value(s[i-1]))%mod;
     }
     v1[h]= 1, v2[h]= x;
     if ( v1[h]>=k ) {
          return 1;
     }

     for ( int i= x+1; i<=n; ++i ) {
          h= (((h-p*value(s[i-1-x]))*sigma+value(s[i-1]))%mod+mod)%mod;
          if ( v2[h]!=x ) {
               v1[h]= 0, v2[h]= x;
          }
          ++v1[h];

          if ( v1[h]>=k ) {
               return 1;
          }
     }

     return 0;
}

int main(  ) {
     fin>>n>>k>>s;

     int sol= 0, step;
     for ( step= 1; step*2<=n; step*= 2 ) ;
     for ( ; step>0; step/= 2 ) {
          if ( sol+step<=n && check(sol+step) ) {
               sol+= step;
          }
     }

     fout<<sol<<"\n";

     return 0;
}