// Use suffix array and LCP to compute // longest common substring of two input strings. BPW #include #include #include char s[1000000],s1[500000],s2[500000]; int n, // length of s[] including \0 sa[1000000], // suffix array for s[] rank[1000000], // rank[i] gives the rank (subscript) of s[i] in sa[] lcp[1000000]; // lcp[i] indicates the number of identical prefix symbols // for s[sa[i-1]] and s[sa[i]] int suffixCompare(const void *xVoidPt,const void *yVoidPt) { // Used in qsort call to generate suffix array. int *xPt=(int*) xVoidPt,*yPt=(int*) yVoidPt; return strcmp(&s[*xPt],&s[*yPt]); } void computeRank() { // Computes rank as the inverse permutation of the suffix array int i; for (i=0;i=lcp[rank[i-1]]-1 for (i=0;i0) h--; // Decrease according to result } } int fibIndex=0; void fib(k) int k; { if (k==0) s[fibIndex++]='1'; else if (k==1) s[fibIndex++]='0'; else { fib(k-1); fib(k-2); } } int main() { int i,j,k,p,dollarPos,LCSpos=0,LCSlength=0; scanf("%s",s1); scanf("%s",s2); for (i=0;s1[i]!='\0';i++) s[i]=s1[i]; dollarPos=i; s[i++]='$'; for (j=0;s2[j]!='\0';j++) s[i+j]=s2[j]; s[i+j]='\0'; n=i+j+1; /* fib(4); fib(6); dollarPos=fibIndex; s[fibIndex++]='$'; fib(5); fib(7); s[fibIndex]='\0'; n=fibIndex+1; */ /* for (i=0;i<1000;i++) s[i]='a'; s[1000]='b'; s[1001]='\0'; */ /* s[0]='a'; for (i=1;i<1000;i++) s[i]='b'; s[1000]='\0'; */ //n=strlen(s)+1; printf("n is %d\n",n); // Quick-and-dirty suffix array construction for (i=0;idollarPos || sa[i-1]>dollarPos && sa[i]LCSlength) { LCSpos=i; LCSlength=lcp[i]; } printf("Length of longest common substring is %d\n",LCSlength); printf("at position %d\n",LCSpos); for (i=0;i