poj 2774(后缀数组)
2015-10-17 13:49
429 查看
题意:每次给出两个串,问两个串的最长公共子串的长度。
题解:后缀数组算法合集之《后缀数组——处理字符串的有力工具》这里讲解的很好,把两个串连接起来,然后求这个串的后缀数组,和对应的height[i]的最大值,但主要要满足sa[i]和sa[i-1]在不同的串中。
题解:后缀数组算法合集之《后缀数组——处理字符串的有力工具》这里讲解的很好,把两个串连接起来,然后求这个串的后缀数组,和对应的height[i]的最大值,但主要要满足sa[i]和sa[i-1]在不同的串中。
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int N = 200005; int wa , wb , ws , wv , sa ; int rank , height , s ; char s1 , s2 ; int cmp(int *r, int a, int b, int l) { return (r[a] == r[b]) && (r[a + l] == r[b + l]); } void DA(int *r, int *sa, int n, int m) { int i, j, p, *x = wa, *y = wb, *t; //计数排序 for (i = 0; i < m; i++) ws[i] = 0; for (i = 0; i < n; i++) ws[x[i] = r[i]]++; for (i = 1; i < m; i++) ws[i] += ws[i - 1]; for (i = n - 1; i >= 0; i--) sa[--ws[x[i]]] = i; for (j = 1, p = 1; p < n; j *= 2, m = p) { //j是长度 //求第二关键字(可以借助之前计算过的sa) for (p = 0, i = n - j; i < n; i++) y[p++] = i; for (i = 0; i < n; i++) if (sa[i] >= j) y[p++] = sa[i] - j; //新一轮排序 for (i = 0; i < n; i++) wv[i] = x[y[i]]; for (i = 0; i < m; i++) ws[i] = 0; for (i = 0; i < n; i++) ws[wv[i]]++; for (i = 0; i < m; i++) ws[i] += ws[i - 1]; for (i = n - 1; i >= 0; i--) sa[--ws[wv[i]]] = y[i]; //求第一关键字 for (t = x, x = y, y = t, p = 1, x[sa[0]] = 0, i = 1; i < n; i++) x[sa[i]] = cmp(y, sa[i - 1], sa[i], j) ? p - 1 : p++; } } void calheight(int *r, int *sa, int n) { int i, j, k = 0; for (i = 1; i <= n; i++) rank[sa[i]] = i; for (i = 0; i < n; height[rank[i++]] = k) for (k ? k-- : 0, j = sa[rank[i] - 1]; r[i + k] == r[j + k]; k++); } int main() { while (scanf("%s%s", s1, s2) == 2) { int len1 = strlen(s1), len2 = strlen(s2), cnt = 0; for (int i = 0; i < len1; i++) s[cnt++] = s1[i] - 'a' + 1; s[cnt++] = 27; for (int i = 0; i < len2; i++) s[cnt++] = s2[i] - 'a' + 1; s[cnt] = 0; DA(s, sa, cnt + 1, 30); calheight(s, sa, cnt); int res = 0; for (int i = 2; i < cnt; i++) if (height[i] > res) { if (sa[i - 1] >= 0 && sa[i - 1] < len1 && sa[i] > len1) res = height[i]; else if (sa[i] >= 0 && sa[i] < len1 && sa[i - 1] > len1) res = height[i]; } printf("%d\n", res); } return 0; }
相关文章推荐
- android四大组件之service生命周期
- Asp.net monitor and telemetry
- DNS中的七大资源记录介绍
- Merge Sorted Array
- Code Forces 586 A. Alena's Schedule(水~)
- 2015-10-15 css3
- SeaJS模块化基础
- java 获取中英混合的字符长度
- poj2686
- Servlet生命周期
- Threejs 它可以在建立其内部房间效果可见
- CodeForces 221D Little Elephant and Array
- QYQ的图
- Cocostudio工具创建工程,因没有字体资源导致在vs中编译时,出现中文乱码现象
- swift 自定义控件在StoryBoard(xib)里使用的属性
- SQL COUNT() 函数
- oracle 11g 64w 用32位的pl/sql
- Struts2部署后抛出404 Tomcat work目录下均为空目录
- 数据结构考研复习--线性表2
- 黑马程序员--C语言指针