Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

第一道后缀数组,留帖纪念

Posted by shjj3 at 2012-06-03 11:18:35 on Problem 2774
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <algorithm>

using namespace std;

char s[500000+33];
int xh[200000+33];
int rank[200000+33],sa[200000+33],trank[200000+33],tsa[200000+33];
int h[200000+33];
int temp[200000+33];
int n,ans;

bool comp(int a,int b)
{return s[a]<s[b];}

int main()
{
scanf("%s",s+1);
int cut1=strlen(s+1);
s[cut1+1]='#';
scanf("%s",s+cut1+2);
int cut2=cut1+2;
n=strlen(s+1);
for (int i=1;i<=n;i++) xh[i]=i;
sort(xh+1,xh+n+1,comp);
int tmp=0;
for (int i=1;i<=n;i++)
  if (s[xh[i]]!=s[xh[i-1]]) 
    rank[xh[i]]=++tmp;
    else rank[xh[i]]=tmp;
int ll=1;
for (;ll<=n;)
  {
  memset(temp,0,sizeof(temp));
  for (int i=1;i<=n;i++) temp[rank[i+ll]]++;
  for (int i=1;i<=n;i++) temp[i]+=temp[i-1];
  for (int i=n;i>=1;i--) tsa[temp[rank[i+ll]]--]=i;
  memset(temp,0,sizeof(temp));
  for (int i=1;i<=n;i++) temp[rank[i]]++;
  for (int i=1;i<=n;i++) temp[i]+=temp[i-1];
  for (int i=n;i>=1;i--) sa[temp[rank[tsa[i]]]--]=tsa[i];
  trank[sa[1]]=1;
  for (int i=2;i<=n;i++)
    if (rank[sa[i-1]]==rank[sa[i]]&&rank[sa[i-1]+ll]==rank[sa[i]+ll])
	  trank[sa[i]]=trank[sa[i-1]];
	  else trank[sa[i]]=trank[sa[i-1]]+1;
  memcpy(rank,trank,sizeof(rank));
  if (rank[sa[n]]==n) break;
  ll=ll<<1;
  }
int l=0;
for (int i=1;i<=n;i++)
  {
  l=max(0,l-1);
  if (rank[i]>1)
    {
	int w=sa[rank[i]-1];
	while (i+l<=n&&w+l<=n&&s[i+l]==s[w+l]) l++;
	h[rank[i]]=l;
	}
	else h[rank[i]]=l=0;
  }
for (int i=2;i<=n;i++)
  if ((sa[i-1]<=cut1&&sa[i]>=cut2)||(sa[i-1]>=cut2&&sa[i]<=cut1))
    ans=max(ans,h[i]);
printf("%d",ans);
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator