Cod sursa(job #51669)

Utilizator pauldbPaul-Dan Baltescu pauldb Data 16 aprilie 2007 10:18:13
Problema Substr Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.8 kb
#include <stdio.h>
#include <vector>
#include <string>

using namespace std;

#define maxn 16384
#define b 73
#define b2 19
#define mod 10429
#define mod2 10000229
#define pb push_back 
#define us unsigned short
#define ll long long

int n,k,sol;
char a[maxn];
vector <us> c[mod];
vector <int> r[mod];
int v[mod];

int add(int x,int x2)
{
    int i;
    
    for (i=0;i<v[x];i++) 
      if (r[x][i]==x2)
      {
           c[x][i]++;
           if (c[x][i]==k) return 1;
           return 0;
      }
      
    c[x].pb(1);
    r[x].pb(x2);
    v[x]++;  
    
    return (k==1);
}

int works(int l)
{
    int i;
    for (i=0;i<mod;i++) 
    {
        c[i].clear();
        r[i].clear();
    }
    
    memset(v,0,sizeof(v));
    int x,y,x2,y2;
    
    y=y2=1;
    x=x2=0;
    
    for (i=l-1;i>=0;i--) 
    {
        x=(x+y*a[i]) % mod;
        if (i>0) y=(y*b) % mod;
        x2=(x2+1LL*y2*a[i]) % mod2;
        if (i>0) y2=(y2*b2) % mod2;
    }
    
    if (add(x,x2)) return 1;
        
    for (i=l;i<n;i++)
    {
        x=(x-y*a[i-l]) % mod;
        if (x<0) x+=mod;
        x=(x*b+a[i]) % mod;
        x2=(x2-1LL*y2*a[i-l]) % mod2;
        if (x2<0) x2+=mod2;
        x2=(x2*b2+a[i]) % mod2;
        
        if (add(x,x2)) return 1;
    }
    
    return 0;
}

int main()
{
    freopen("substr.in","r",stdin);
    freopen("substr.out","w",stdout);
    
    scanf("%d %d ",&n,&k);
    
    fgets(a,maxn,stdin);
    
    int front=1,middle,back=n;
        
    while (front<=back)
    {
          middle=(front+back)/2;
          
          if (works(middle))
          {
               sol=middle;
               front=middle+1;
          }
          else back=middle-1;
    }
    
    printf("%d\n",sol);
    
    return 0;
}