码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 3415 Common Substrings

时间:2015-04-16 19:57:25      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:后缀数组   单调栈   

单调栈的思想很巧妙,若进入的元素比栈顶小,则栈顶出栈,把相应信息更新一下,直到要进入的元素比栈顶元素大

//注意这道题和Facer’s string这道题的区别
//该题求的是sa[i]-sa[j]的lcp,需要用到的是height[i+1]-height[j]
//而 Facer’s string这道题用到的是height[i]-height[j]的值,涉及到的是sa[i-1]-sa[j]
 
#include<stdio.h> 
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long ll;
#define N 100005
char s[N];
int r[N],sa[N],height[N],rank[N],wa[N],wb[N],wv[N],ws[N]; 
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 *sa,int n,int m){
	int i,j,p,*x=wa,*y=wb;
	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;m=p,j<<=1){
		for(i=n-j,p=0;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];
		swap(x,y);
		for(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 *sa,int n){
	int i,j,k=0;
	for(i=1;i<=n;i++) rank[sa[i]]=i;
	for(i=0;i<n;height[rank[i++]]=k)
		for(k?k--:0,j=sa[rank[i]-1];r[i+k]==r[j+k];k++);
	//for(i=1;i<=n;i++) printf("%d ",height[i]);
}
int sta[N][2];
int main(){
	#ifndef ONLINE_JUDGE
	freopen("in.txt","r",stdin);
	#endif
	int k;
	while(scanf("%d",&k),k){
		scanf("%s",s);
		int n1=strlen(s),l=0;
		for(int i=0;i<n1;i++) r[l++]=s[i];
		r[l++]=129;
		scanf("%s",s);
		int n2=strlen(s);
		for(int i=0;i<n2;i++) r[l++]=s[i];
		r[l]=0;
		da(r,sa,l+1,130);
		calheight(r,sa,l);
		int bot=0,top=0;
		ll ans=0,t=0;
		for(int i=1;i<=l;i++){
			if(height[i]<k){
				bot=0,top=0,t=0;
			}
			else{
				int weight=0;
				if(sa[i-1]<n1) weight++,t+=height[i]-k+1;//如果前一个串是B串,那么当前串是没有贡献的,因为当前的height值实际上记录的是前一个串与后面的串的lcp 
				while(top>bot&&height[i]<=sta[top-1][0]) {
					t-=(sta[top-1][0]-height[i])*sta[top-1][1];//减去差值 
					weight+=sta[top-1][1];
					top--;
				}
				sta[top][0]=height[i];
				sta[top++][1]=weight;
				if(sa[i]>n1) ans+=t;//如果当前串是B串(注意是sa[i],不是sa[i-1]),则加上前面的总和 
			}
		}
		t=0,bot=0,top=0;
		for(int i=1;i<=l;i++){
			if(height[i]<k){
				bot=0,top=0,t=0;
			}
			else{
				int weight=0;
				if(sa[i-1]>n1) weight++,t+=height[i]-k+1;
				while(top>bot&&height[i]<=sta[top-1][0]) {
					t-=(sta[top-1][0]-height[i])*sta[top-1][1];
					weight+=sta[top-1][1];
					top--;
				}
				sta[top][0]=height[i];
				sta[top++][1]=weight;
				if(sa[i]<n1) ans+=t;
			}
		}
		printf("%I64d\n",ans);
	}
}

POJ 3415 Common Substrings

标签:后缀数组   单调栈   

原文地址:http://blog.csdn.net/lj94093/article/details/45079269

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!