HDU 1403 Longest Common Substring

来源:互联网 发布:sql数据修复工具 编辑:程序博客网 时间:2024/06/09 18:36
Problem Description
Given two strings, you have to tell the length of the Longest Common Substring of them.

For example:
str1 = banana
str2 = cianaic

So the Longest Common Substring is "ana", and the length is 3.
 

Input
The input contains several test cases. Each test case contains two strings, each string will have at most 100000 characters. All the characters are in lower-case.

Process to the end of file.
 

Output
For each test case, you have to tell the length of the Longest Common Substring of them.
 

Sample Input
bananacianaic
 

Sample Output
3

后缀数组的应用

#include<iostream>#include<cmath>#include<map>#include<vector>#include<queue>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn = 200005;class suffix{private:char s[maxn];int r[maxn], w[maxn], ss[maxn], h[maxn];int sa[maxn], rk[maxn + maxn], size, bit = 256;int size1;public:bool get(){ if (scanf("%s", s + 1) != 1) return false;size1 = strlen(s + 1);scanf("%s", s + size1 + 2);s[++size1] = 1;size = strlen(s + 1);return true;}void pre(){memset(rk, 0, sizeof(rk));for (int i = 1; i <= bit; i++) w[i] = 0;for (int i = 1; i <= size; i++) w[(int)s[i]]++;for (int i = 1; i <= bit; i++) w[i] += w[i - 1];for (int i = size; i; i--) sa[w[(int)s[i]]--] = i;for (int i = 1, j = 1; i <= size; i++)rk[sa[i]] = (s[sa[i]] == s[sa[i + 1]] ? j : j++);for (int j = 1; j < size; j += j){for (int i = 1; i <= size; i++) w[i] = 0;for (int i = 1; i <= size; i++) w[rk[i + j]]++;for (int i = 1; i <= size; i++) w[i] += w[i - 1];for (int i = size; i; i--) ss[w[rk[i + j]]--] = i;for (int i = 1; i <= size; i++) w[i] = 0;for (int i = 1; i <= size; i++) w[rk[ss[i]]]++;for (int i = 1; i <= size; i++) w[i] += w[i - 1];for (int i = size; i; i--) sa[w[rk[ss[i]]]--] = ss[i];for (int i = 1, k = 1; i <= size; i++)r[sa[i]] = (rk[sa[i]] == rk[sa[i + 1]] && rk[sa[i] + j] == rk[sa[i + 1] + j]) ? k : k++;for (int i = 1; i <= size; i++) rk[i] = r[i];}for (int i = 1, k = 0, j; i <= size; h[rk[i++]] = k)for (k ? k-- : 0, j = sa[rk[i] - 1]; s[i + k] == s[j + k]; k++);}void work(){int mid = (size1 - 1) >> 1;for (int l = 0, r = size1 - 1,f; l < r;){f = 0;for (int i = 2, j; i <= size; i = j + 1){int f1 = 0, f2 = 0;for (j = i; h[j] >= mid; j++){if (sa[j] < size1) f1 = 1; else f2 = 1;if (sa[j - 1] < size1) f1 = 1; else f2 = 1;if (f1 && f2) { f = 1; goto end; }}}end:;if (f) l = mid; else r = mid - 1;mid = (l + r) >> 1;if (mid == l) mid = r;}printf("%d\n", mid);}}f;int main(){while (f.get()){f.pre();f.work();}return 0;}


0 0
原创粉丝点击