poj 3415 Common Substrings

    xiaoxiao2021-04-17  42

    Common Substrings Time Limit: 5000MS Memory Limit: 65536K Total Submissions: 10835 Accepted: 3578 Description

    A substring of a string T is defined as:

    T(i, k)=TiTi+1…Ti+k-1, 1≤i≤i+k-1≤|T|. Given two strings A, B and one integer K, we define S, a set of triples (i, j, k):

    S = {(i, j, k) | k≥K, A(i, k)=B(j, k)}. You are to give the value of |S| for specific A, B and K.

    Input

    The input file contains several blocks of data. For each block, the first line contains one integer K, followed by two lines containing strings A and B, respectively. The input file is ended by K=0.

    1 ≤ |A|, |B| ≤ 105 1 ≤ K ≤ min{|A|, |B|} Characters of A and B are all Latin letters.

    Output

    For each case, output an integer |S|.

    Sample Input

    2 aababaa abaabaa 1 xx xx 0 Sample Output

    22 5 Source

    POJ Monthly–2007.10.06, wintokk


    【分析】 后缀数组的应用:求两个字符串的最长公共子串 用一个$把两个串连起来,然后跑一边height,统计height最大值(注意两个子串不能再同一个原串中,这需要判断一下)


    【代码】

    //poj 2774 #include<iostream> #include<cstring> #include<cstdio> #define ll long long #define M(a) memset(a,0,sizeof a) #define fo(i,j,k) for(i=j;i<=k;i++) using namespace std; const int mxn=1000005; int n,m,len,ans; int a[mxn],sa[mxn],height[mxn],rank[mxn],x[mxn],y[mxn],b[mxn]; char s[mxn]; inline bool comp(int i,int j,int l) { return y[i]==y[j] && (i+l>len?-1:y[i+l])==(j+l>len?-1:y[j+l]); } inline void work() { m=200; int i,j,k,p; fo(i,0,m) b[i]=0; fo(i,1,len) b[x[i]=a[i]]++; fo(i,1,m) b[i]+=b[i-1]; for(i=len;i>=1;i--) sa[b[x[i]]--]=i; for(k=1;k<=len;k<<=1) { p=0; fo(i,len-k+1,len) y[++p]=i; fo(i,1,len) if(sa[i]>k) y[++p]=sa[i]-k; fo(i,0,m) b[i]=0; fo(i,1,len) b[x[y[i]]]++; fo(i,1,m) b[i]+=b[i-1]; for(i=len;i>=1;i--) sa[b[x[y[i]]]--]=y[i]; swap(x,y),p=2,x[sa[1]]=1; fo(i,2,len) x[sa[i]]=comp(sa[i-1],sa[i],k)?p-1:p++; if(p>len) break; m=p; } p=k=0; fo(i,1,len) rank[sa[i]]=i; for(i=1;i<=len;height[rank[i++]]=k) for(k?k--:0,j=sa[rank[i]-1];a[i+k]==a[j+k];k++); } int main() { int hal,i,j,k,tmp; scanf("%s",s+1); tmp=strlen(s+1); s[++tmp]='$';hal=tmp; fo(i,1,tmp) a[i]=s[i]; scanf("%s",s+1); len=strlen(s+1); fo(i,1,len) a[++tmp]=s[i]; len=tmp; // fo(i,1,len) printf("a[%d]=%d\n",i,a[i]); work(); fo(i,2,len) if((sa[i]<hal && sa[i-1]>hal) || (sa[i]>hal && sa[i-1]<hal)) ans=max(ans,height[i]); printf("%d\n",ans); return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-674375.html

    最新回复(0)