POJ 3415 Common Substrings(后缀数组+单调栈)

转载请注明出处,谢谢http://blog.csdn.net/acm_cxlove/article/details/7854526       by---cxlove 

题目:求出长度不小于k的公共子串个数

http://poj.org/problem?id=3415 

继续论文上的题目。

计算A的某个后缀与B的某个后缀的最长公共前缀长度,如果长度L大于k,则加上L-k+1组。

将两个字符串连接起来,中间用一个没有出现的字符分开。(这是一个神奇的做法)

然后通过height数组分组,某个组内的height都是大于等于k的,也就是任意两个后缀的最长公共前缀都至少为k。

扫描一遍,遇到一个B的后缀就与之前的A后缀进行统计,求出所有的满足的组数。但是这样的做法便是n^2的。

可以发现两个后缀的最长公共前缀为这一段的height值的最小值。

可以通过一个单调栈来维护一下,当前要入栈元素如果小于栈底元素,说明之后加入的B后缀与栈底的最长公共前缀是小于等于入栈的。这样就保证了单调栈内的height值是绝对递增的,逐渐合并,均摊可以达到o(n)的复杂度。

然后扫描两遍即可

#include
#include
#include
#include
#include
#define N 100005
#define LL long long
#define maxn 200005
using namespace std;
//以下为倍增算法求后缀数组  
int wa[maxn],wb[maxn],wv[maxn],Ws[maxn];  
int cmp(int *r,int a,int b,int l)  
{return r[a]==r[b]&&r[a+l]==r[b+l];}  
void da(const char *r,int *sa,int n,int m){  
	int i,j,p,*x=wa,*y=wb,*t;   
	for(i=0;i=0;i--) sa[--Ws[x[i]]]=i;   
	for(j=1,p=1;p=j) y[p++]=sa[i]-j;   
		for(i=0;i=0;i--) sa[--Ws[wv[i]]]=y[i];   
		for(t=x,x=y,y=t,p=1,x[sa[0]]=0,i=1;i0&&height[i]<=s[top-1][0]){
					top--;
					tot-=s[top][1]*(s[top][0]-height[i]);
					cnt+=s[top][1];
				}
				s[top][0]=height[i];s[top++][1]=cnt;
				if(sa[i]>l1) sum+=tot;
			}
		}
		tot=top=0;
		for(int i=1;i<=n;i++){
			if(height[i]l1) cnt++,tot+=height[i]-k+1;
				while(top>0&&height[i]<=s[top-1][0]){
					top--;
					tot-=s[top][1]*(s[top][0]-height[i]);
					cnt+=s[top][1];
				}
				s[top][0]=height[i];s[top++][1]=cnt;
				if(sa[i]


你可能感兴趣的:(ACM_字符串)