Cod sursa(job #420)

Utilizator alextheroTandrau Alexandru alexthero Data 11 decembrie 2006 11:03:15
Problema Substr Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.1 kb
#include <stdio.h>
#include <algorithm>
#define nmax 16384

using namespace std;

int n,k,sa[nmax];
char a[nmax];

int cmp(int x,int y) {
    int i=x,j=y;
    while ((a[i]==a[j]) && (i<n) && (j<n)) {
          i++; j++;
    }
    if(a[i]>a[j]) return 0;
    else return 1;
}

int maimic(int poz,int f,int l) {
// returneaza 1 daca stringul din sa de la pozitia poz este mai mic decat cel care incepe la pozitia f si are l caractere
   int i=sa[poz],j=sa[f],cate=0;
   while ((a[i]!=a[j]) && (i<n) && (cate<l)) {
         i++; j++; cate++;
         }
   if((cate==l) && (a[i]==a[j])) return 3;
   if(a[i]<a[j]) return 1;
   else if(a[i]>a[j]) return 2;
   return 3;
}

int cauta1(int first, int last,int f, int l) {
    int rez=-1;
    while(first<=last) {
                       int middle=(first+last)/2;
                       int x=maimic(middle,f,l);
                       if(x==1) first=middle+1;
                       else if(x>1) {
                            last=middle-1;
                            if(x==3) rez=middle;
                       }
    }
    return rez;
}

int howmany(int f,int l) {
   int first=cauta1(0,n-1,f,l);
   if(first==-1) return 0;
   if(maimic(first+k-1,f,l)==2) return k;
   else return 0;
}

int ok(int l) {
   for(int i=0;i<n-l;i++) {
           int cate=howmany(i,l);
           if(cate==k) return 1;        
   }
   return 0;
}

int cauta(int first,int last) {
    int rez=0;
    while(first<=last) {
                       int middle=(first+last)/2;
                       if(ok(middle)) {
                                      rez=middle;
                                      first=middle+1;
                                      }
                       else last=middle-1;
                       }   
    return rez;
}

int main() {
    freopen("substr.in","r",stdin);
    freopen("substr.out","w",stdout);
    
    scanf("%d %d\n",&n,&k);
    for(int i=0;i<n;i++) {
            scanf("%c",&a[i]);
            sa[i]=i;
    }
    
    sort(sa,sa+n,cmp);    
    
    printf("%d\n",cauta(0,n-1));
    return 0;
}