标签:
1 #include<cstdlib> 2 #include<cstdio> 3 #include<algorithm> 4 #include<cstring> 5 #define rep(i,a,b) for(i = a; i < b; ++i) 6 #define rev(i,a,b) for(i = a; i >= b; --i) 7 using namespace std; 8 const int maxn = (int)2500, inf = 0x3f3f3f3f; 9 int sa[maxn],rank[maxn],height[maxn],t1[maxn],t2[maxn],c[maxn]; 10 char str[maxn]; 11 int n; 12 int cmp(int x[],int a,int b,int c){ 13 return x[a] == x[b] && x[a+c] == x[b+c]; 14 } 15 void build(int m){ 16 int i,j,p = 0, *x = t1, *y = t2; 17 rep(i,0,m) c[i] = 0; 18 rep(i,0,n) c[x[i] = str[i]]++; 19 rep(i,1,m) c[i] += c[i-1]; 20 rev(i,n-1,0) sa[--c[x[i]]] = i; 21 for(j = 1; j < n && p < n; j <<= 1, m = p){ 22 p = 0; 23 rep(i,n-j,n) y[p++] = i; 24 rep(i,0,n) if(sa[i] >= j) y[p++] = sa[i] - j; 25 rep(i,0,m) c[i] = 0; 26 rep(i,0,n) c[x[y[i]]]++; 27 rep(i,1,m) c[i] += c[i-1]; 28 rev(i,n-1,0) sa[--c[x[y[i]]]] = y[i]; 29 for(swap(x,y), p = 1, x[sa[0]] = 0, i = 1; i < n; ++i) 30 x[sa[i]] = cmp(y,sa[i-1],sa[i],j) ? p - 1 : p++; 31 } 32 } 33 void calc_height(){ 34 int i,j,k = 0; 35 rep(i,0,n) rank[sa[i]] = i; 36 for(i = 0; i < n; height[rank[i++]] = k) 37 for(k ? k-- : 0, j = sa[rank[i] - 1]; str[i+k] == str[j+k] && min(i,j) + k < n; k++); 38 } 39 int l,r,lcp,last,ret; 40 int getlen(int st,int ed){ 41 return ed - st + 1; 42 } 43 int calc(int now,int pas){ 44 int la = getlen(sa[now],r), lb = getlen(sa[pas],r); 45 return pas ? la - min(lcp,min(lb,la)) : la; 46 } 47 int getnext(int now,int pas){ 48 if(!pas) return now; 49 int la = getlen(sa[now],r), lb = getlen(sa[pas],r); 50 if(lcp < min(la,lb)) return now; 51 if(lcp >= la && lcp >= lb && la > lb) return now; 52 if(lcp < la && lcp >= lb) return now; 53 return pas; 54 } 55 void solve(){ 56 int i; 57 ret = last = 0; lcp = inf; 58 rep(i,0,n){ 59 if(l <= sa[i] && sa[i] <= r){ 60 if(last) lcp = min(lcp,height[i]); 61 ret += calc(i,last); 62 int t = getnext(i,last); 63 if(t == i) lcp = getlen(sa[i],r), last = i; 64 } 65 else if(last) lcp = min(lcp, height[i]); 66 } 67 printf("%d\n",ret); 68 } 69 int main() 70 { 71 freopen("rec.in","r",stdin); 72 freopen("rec.out","w",stdout); 73 int T,q; 74 scanf("%d\n",&T); 75 while(T--){ 76 scanf("%s",str); 77 n = strlen(str); 78 str[n++] = ‘a‘ - 1; 79 build(255); 80 calc_height(); 81 scanf("%d\n",&q); 82 while(q--){ 83 scanf("%d %d\n",&l,&r); 84 l--; r--; 85 solve(); 86 } 87 } 88 return 0; 89 }
标签:
原文地址:http://www.cnblogs.com/Mr-ren/p/4220007.html