POJ 2774 (后缀数组 最长公共字串) Long Long Message

用一个特殊字符将两个字符串连接起来,然后找最大的height,而且要求这两个相邻的后缀的第一个字符不能在同一个字符串中。

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 const int maxn = 200000 + 10;
 7 
 8 char s[maxn];
 9 int n;
10 int sa[maxn], rank[maxn], height[maxn];
11 int t[maxn], t2[maxn], c[maxn];
12 
13 void build_sa(int n, int m)
14 {
15     int i, *x = t, *y = t2;
16     for(i = 0; i < m; i++) c[i] = 0;
17     for(i = 0; i < n; i++) c[x[i] = s[i]]++;
18     for(i = 1; i < m; i++) c[i] += c[i - 1];
19     for(i = n - 1; i >= 0; i--) sa[--c[x[i]]] = i;
20     for(int k = 1; k <= n; k <<= 1)
21     {
22         int p = 0;
23         for(i = n - k; i < n; i++) y[p++] = i;
24         for(i = 0; i < n; i++) if(sa[i] >= k) y[p++] = sa[i] - k;
25         for(i = 0; i < m; i++) c[i] = 0;
26         for(i = 0; i < n; i++) c[x[y[i]]]++;
27         for(i = 1; i < m; i++) c[i] += c[i - 1];
28         for(i = n - 1; i >= 0; i--) sa[--c[x[y[i]]]] = y[i];
29         swap(x, y);
30         p = 1; x[sa[0]] = 0;
31         for(i = 1; i < n; i++)
32             x[sa[i]] = y[sa[i]]==y[sa[i-1]] && y[sa[i]+k]==y[sa[i-1]+k] ? p - 1 : p++;
33         if(p >= n) break;
34         m = p;
35     }
36 }
37 
38 void build_height()
39 {
40     int k = 0;
41     for(int i = 1; i <= n; i++) rank[sa[i]] = i;
42     for(int i = 0; i < n; i++)
43     {
44         if(k) k--;
45         int j = sa[rank[i] - 1];
46         while(s[i + k] == s[j + k]) k++;
47         height[rank[i]] = k;
48     }
49 }
50 
51 int main()
52 {
53     //freopen("in.txt", "r", stdin);
54 
55     scanf("%s", s);
56     int pos = strlen(s);
57     s[pos] = 1;
58     scanf("%s", s + pos + 1);
59     n = strlen(s);
60 
61     build_sa(n + 1, 256);
62     build_height();
63 
64     int ans = 0;
65     for(int i = 2; i <= n; i++)
66     {
67         if(height[i] > ans)
68         {
69             if((sa[i]>pos && sa[i-1]<pos) || (sa[i]<pos&&sa[i-1]>pos))
70                 ans = height[i];
71         }
72     }
73 
74     printf("%d\n", ans);
75 
76     return 0;
77 }
代码君

 

posted @ 2015-04-23 22:34  AOQNRMGYXLMV  阅读(176)  评论(0编辑  收藏  举报