学后缀数组快学死我了,学了三天,才懂了点大概,那命做了个模板题,然后推荐一个好的后缀数组博客https://blog.csdn.net/j_sure/article/details/41777097#就是它救了我的命
#include <iostream> #include <cstring> #include <algorithm> #include <cstdio> #include <set> #include <vector> using namespace std; const int maxn=400000+100; int s[maxn];//不用int会re int c[maxn],t[maxn],t2[maxn],sa[maxn]; int Rank[maxn],height[maxn]; int id[maxn]; int N,n; void build(int m) { int i,*x = t,*y = t2; for(i = 0; i < m; i++) c[i] = 0; for(i = 0; i < n; i++) c[x[i]=s[i]]++; for(i = 1; i < m; i++) c[i] += c[i-1]; for(i = n-1; i >= 0; i--) sa[--c[x[i]]] = i; for(int k = 1; k <= n; k <<= 1) { int p = 0; for(i = n-k; i < n; i++) y[p++] = i; for(i = 0; i < n; i++) if(sa[i] >= k)y[p++] = sa[i] - k; for(i = 0; i < m; i++) c[i] = 0; for(i = 0; i < n; i++) c[x[y[i]]]++; for(i = 0; i < m; i++) c[i] += c[i-1]; for(i = n-1; i >= 0; i--) sa[--c[x[y[i]]]] = y[i]; swap(x,y); p = 1; x[sa[0]] = 0; for(i = 1; i < n; i++) x[sa[i]] = y[sa[i-1]] == y[sa[i]] && y[sa[i-1] + k] == y[sa[i]+k] ? p-1:p++; if(p >= n) break; m = p; } } void getHeight() { int i,j,k = 0; for(i = 0; i < n; i++) Rank[sa[i]] = i; for(i = 0; i < n; i++) { if(k) k--; if (Rank[i] == 0) continue; int j = sa[Rank[i]-1]; while(s[i+k] == s[j+k]) k++; height[Rank[i]] = k; } } bool judge(int l,int flag) { set<int> ss; ss.insert(id[sa[0]]); for(int i=1; i<n; i++) { while(i<n&&height[i]>=l) { ss.insert(id[sa[i]]); i++; } if(ss.size()*2>N) { if(!flag) return 1; for(int j=0;j<l;j++) printf("%c",s[sa[i-1]+j]); printf("\n"); } ss.clear(); ss.insert(id[sa[i]]); } return 0; } int main() { int Case=0; while(~scanf("%d",&N)&&N) { if(Case) printf("\n"); Case++; int maxi=0; n=0; getchar(); char word[2000]; if(N==1) { scanf("%s",word); printf("%s\n",word); } else { for(int i=0; i<N; i++) { scanf("%s",word); int mm=strlen(word); maxi=max(maxi,mm); for(int j=0; j<mm; j++) { id[n]=i; s[n++]=word[j]; } id[n]=i; s[n++]=‘z‘+i+1; } build(‘z‘+N+1); getHeight(); if(!judge(1,0)) printf("?\n"); else { int l=1,r=maxi+1; while(l<r) { int mid=(l+r)/2; if(judge(mid,0)) l=mid+1; else r=mid; } judge(l-1,1); } } } return 0; }
原文:https://www.cnblogs.com/Wangwanxiang/p/9286424.html