Cod sursa(job #267)

Utilizator pauldbPaul-Dan Baltescu pauldb Data 8 decembrie 2006 12:04:28
Problema Substr Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.3 kb
#include <stdio.h>

#define maxn 16394
#define baza 79
#define mod 4999999

int n,sol,k;
char a[maxn];
long c[mod],p[maxn];

int fix(char c)
{
    if ((c>='a') && (c<='z')) return c-'a';
    if ((c>='A') && (c<='Z')) return c-'A'+26;
    return c-'0'+52;
}

int works(long m)
{
	long x,y,max=0,i,l=0,z;
	x=0;
	y=1;

	for (i=m-1;i>=0;i--)
	{
        z=fix(a[i]);
		x=(x+y*z) % mod;
		if (i>0) y=(y*baza) % mod;
	}

	c[x]++;
	max=c[x];
	
	for (i=m;i<=n;i++)
	{
        z=fix(a[i-m]);
		x=(x-y*z) % mod;

		if (x<0) x=x+mod;

        x=(x*baza)%mod;
        z=fix(a[i]);
		x=(x+z)%mod;
		if (c[x]==0)
		{
		   l++;
		   p[l]=x;
		}
        c[x]++;
        if (c[x]>max) max=c[x];
	}

	for (i=1;i<=l;i++) c[p[i]]=0;
    
    if (max>=k) return 1;
    else return 0;
}

int main()
{
    freopen("substr.in","r",stdin);
    freopen("substr.out","w",stdout);
    
    scanf("%d %d ",&n,&k);
    
    fgets(a,n+2,stdin);
    n--;
	long i;
	    	  	  	      
	long front,back,middle;
    front=1;
	back=n+1;
    
    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;
}