Cod sursa(job #221719)

Utilizator gabitzish1Gabriel Bitis gabitzish1 Data 17 noiembrie 2008 19:40:45
Problema Substr Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.87 kb
#include <cstdio>
#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 verif(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 p, u, m;
	p = 1; u = n;
        
    while (p <= u)
    {
          m = (p + u) / 2;
          
          if (verif(m))
          {
               sol = m;
               p = m + 1;
          }
          else u = m - 1;
    }
    
    printf("%d\n",sol);
    
    return 0;
}