poj 3415 后缀数组+单调栈

题目大意:

求两个字符串的长度大于k的公共子串的个数(可以相同)

基本思路:

后缀数组+单调栈,就是降低复杂度到O(n);

代码如下:

#include<cstdio>
#include<cstring>
using namespace std;

typedef  long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 200000+10;
int wa[maxn],wb[maxn],wv[maxn],ws[maxn],sa[maxn],ranks[maxn],height[maxn];
char str[maxn];
int s[maxn];
int q[maxn][2];
int num;
int cmp(int *r,int a,int b,int l){
    return r[a]==r[b]&&r[a+l]==r[b+l];
}
void da(int *r,int n,int m){
    int i,j,p,*x=wa,*y=wb,*t;
    for(i=0;i<m;i++) ws[i]=0;
    for(i=0;i<n;i++) ws[x[i]=r[i]]++;
    for(i=1;i<m;i++) ws[i]+=ws[i-1];
    for(i=n-1;i>=0;i--) sa[--ws[x[i]]]=i;
    for(j=1,p=1;p<n;j*=2,m=p){
        for(p=0,i=n-j;i<n;i++) y[p++]=i;
        for(i=0;i<n;i++) if(sa[i]>=j) y[p++]=sa[i]-j;
        for(i=0;i<n;i++) wv[i]=x[y[i]];
        for(i=0;i<m;i++) ws[i]=0;
        for(i=0;i<n;i++) ws[wv[i]]++;
        for(i=1;i<m;i++) ws[i]+=ws[i-1];
        for(i=n-1;i>=0;i--) sa[--ws[wv[i]]]=y[i];
        for(t=x,x=y,y=t,p=1,x[sa[0]]=0,i=1;i<n;i++) x[sa[i]]=cmp(y,sa[i-1],sa[i],j)?p-1:p++;
    }
}
void calHeight(int *r,int n){
    int i,j,k=0;
    for(i=1;i<=n;i++) ranks[sa[i]]=i;
    for(i=0;i<n;i++){
        if(k) k-=1;
        j=sa[ranks[i]-1];
        while(r[i+k]==r[j+k]) k++;
        height[ranks[i]]=k;
    }
}
ll solve(int len1,int len2,int cnt_){
    ll ans=0,tot=0,cnt=0;
    int top=0;
    for(int i=2;i<=cnt_;i++){
        if(height[i]<num){
            top=tot=0;
            continue;
        }
        cnt=0;
        if(sa[i-1]<len1){
            cnt++;
            tot+=(height[i]-num+1);
        }
        while(top&&height[i]<=q[top][0]){
            tot-=q[top][1]*(q[top][0]-height[i]);
            cnt+=q[top][1];
            top--;
        }
        q[++top][0]=height[i];
        q[top][1]=cnt;
        if(sa[i]>len1) ans+=tot;
    }
    tot=top=0;
    for(int i=2;i<=cnt_;i++){
        if(height[i]<num){
            tot=top=0;
            continue;
        }
        cnt=0;
        if(sa[i-1]>len1){
            cnt++;
            tot+=height[i]-num+1;
        }
        while(top&&height[i]<=q[top][0]){
            tot-=q[top][1]*(q[top][0]-height[i]);
            cnt+=q[top][1];
            top--;
        }
        q[++top][0]=height[i];
        q[top][1]=cnt;
        if(sa[i]<len1) ans+=tot;
    }
    return ans;
}
int main(){
    while(scanf("%d",&num)==1&&num){
        scanf("%s",str);
        int len=strlen(str);
        int cnt=0;
        for(int i=0;i<len;i++){
            s[cnt++]=(int)str[i];
        }
        s[cnt++]=259;
        scanf("%s",str);
        int len2=strlen(str);
        for(int i=0;i<len2;i++){
            s[cnt++]=(int)str[i];
        }
        s[cnt]=0;
        da(s,cnt+1,260);
        calHeight(s,cnt);
        ll ans=solve(len,len2,cnt);
        printf("%lld
",ans);
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/imzscilovecode/p/8000380.html