POJ
来源:互联网 发布:大数据能做什么 编辑:程序博客网 时间:2024/06/08 12:36
POJ - 3415
将两个串通过一个中间字符连接到一起,然后求出
设两个串为
将后缀
维护一个单调递增栈,每次一个后缀
#include<algorithm>#include<cstdio>#include<cstring>using namespace std;typedef long long ll;const int N = 2e5+7;int sa[N],c[N],t1[N],t2[N],rk[N],h[N],dp[N][20],mm[N];int n;char s[N];bool cmp(int *r, int a, int b, int l){ return r[a] == r[b] && r[a+l] == r[b+l] ;}//最后得到的 rk 在[0,n-1] 有效//h和sa均在[1,n]内有效void get_sa(char *s,int *sa,int *h,int *rk,int n,int m){ s[n]=0; ++n; //++n的原因是因为最后引入了一个0,因此预处理后显然sa[oldn]=0。 int p, *x = t1, *y = t2; //基数排序:计算每个值的cnt,然后计算cnt的前缀和,标志每种值的在sa数组中的区间, //然后将下标(后缀第一个字母的位置)放置到sa数组中。 for(int i=0;i<m;++i) c[i]=0; for(int i=0;i<n;++i) ++c[x[i]=s[i]]; for(int i=1;i<m;++i) c[i]+=c[i-1]; for(int i=n-1;i>=0;--i) sa[--c[x[i]]]=i; //k是倍增的大小,新的数组中,(x[i],x[i+k])是一个pair。 //k<=n 因为极限情况是0+n==n。 for(int k=1;k<=n;k<<=1) { //sa倍增 //y是pair中第二个关键字排好序后对应的第一个关键字的下标。 //当sa[i]>=k时,才有第一个关键字。 p=0; for(int i=n-k;i<n;++i) y[p++]=i; for(int i=0;i<n;++i) if(sa[i]>=k) y[p++]=sa[i]-k; //基数排序,不过这里计算sa的时候根据y从后往前,因为考虑到第一关键字相同时,第二个关键字也是要升序的。 //x相当于s吧,不过每次被增后x会发生变化。 for(int i=0;i<m;++i) c[i]=0; for(int i=0;i<n;++i) ++c[x[i]]; //这里和邝斌的不一样 for(int i=1;i<m;++i) c[i]+=c[i-1]; for(int i=n-1;i>=0;--i) sa[--c[x[y[i]]]]=y[i]; swap(x,y); p=1;x[sa[0]]=0; //sa[0]=n-1,相当于x[n-1]=0。 //给x赋新值,根据sa[i]升序,这样保证p最小。且相同的pair值一样。 for(int i=1;i<n;++i) x[sa[i]] = cmp(y,sa[i-1],sa[i],k) ? p-1:p++; if(p>=n) break; //不同的值已经达到n就退出。 m=p; //x中的最大值+1。 } int k=0,j; --n; for(int i=0;i<=n;++i) rk[sa[i]]=i; //rk[n]=0 //for(int i=0;i<n;++i) printf("%d\n",rk[i]); //h[rk[i]]>=h[rk[i]-1]-1 。 for(int i=0;i<n;++i) { if(k) --k; j=sa[rk[i]-1]; while(s[i+k]==s[j+k]) ++k; h[rk[i]]=k; }}int top,len[N];int main(){ int k; while(~scanf("%d",&k)) { if(k==0) break; scanf("%s",s); int mid=strlen(s); s[mid]='.'; scanf("%s",s+mid+1); n=strlen(s); get_sa(s,sa,h,rk,n,128); top=0; ll ans = 0,res=0; for(int i=1;i<=n;++i) { if(h[i]<k) top=res=0; else { int num = 0; if(sa[i-1]<mid) ++num,res+=h[i]-k+1; while(top&&len[top-1]>=h[i]) { res-=(ll)(len[top-1]-h[i])*c[top-1]; num+=c[top-1]; --top; } c[top]=num;len[top]=h[i];++top; if(sa[i]>mid) ans+=res; } } res=top=0; for(int i=1;i<=n;++i) { if(h[i]<k) top=0,res=0; else { int num=0; if(sa[i-1]>mid) ++num,res+=h[i]-k+1; while(top&&len[top-1]>=h[i]) { res-=(ll)(len[top-1]-h[i])*c[top-1]; num+=c[top-1]; --top; } c[top]=num;len[top]=h[i];++top; if(sa[i]<mid) ans+=res; } } printf("%I64d\n",ans); } return 0;}
阅读全文
0 0
- POJ
- poj
- POJ
- POJ
- poj
- poj
- POJ
- POJ
- poj
- POJ
- POJ
- POJ
- POJ
- POJ
- POJ
- POJ
- POJ
- POJ
- 利用for循环求100~200内的素数
- java关键字native、static、final详解
- 决策树学习 -- ID3算法和C4.5算法(C++实现)
- python把Excel数组转化为文本
- typeScript入门
- POJ
- PX4飞控学习(五)
- Excel经纬度转Shp
- 四大线程池详解
- An Introduction to Flask 12~15
- MySQL存储引擎---MyISAM与InnoDB区别
- C++栈的用法及栈的实现
- 业余时间决定了你人生的高度
- Java:按值传递还是按引用传递详细解说