题目大意:
就是对于给出两个长度都为N的只包含大写字母的串求其最长公共子串
存在多个长度相同的的串时输出任意一个
大致思路:
就是一个简单的后缀数组的题...很简单了...
细节见代码
代码如下:
Result : Accepted Memory : 6774 KB Time : 218 ms
/* * Author: Gatevin * Created Time: 2015/2/9 16:05:51 * File Name: Iris_Freyja.cpp */ #include<iostream> #include<sstream> #include<fstream> #include<vector> #include<list> #include<deque> #include<queue> #include<stack> #include<map> #include<set> #include<bitset> #include<algorithm> #include<cstdio> #include<cstdlib> #include<cstring> #include<cctype> #include<cmath> #include<ctime> #include<iomanip> using namespace std; const double eps(1e-8); typedef long long lint; #define maxn 233333 /* * Doubling Algorithm 求后缀数组 */ int wa[maxn], wb[maxn], wv[maxn], Ws[maxn]; 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 *x = wa, *y = wb, *t, i, j, p; 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) { 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 = 1; 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++; } return; } int rank[maxn], height[maxn]; 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++); return; } int N; int s[maxn], sa[maxn]; char tmp[maxn >> 1]; int start; bool check(int mid, int n) { for(int i = 1; i <= n; i++) if(height[i] >= mid) { if(((lint)sa[i] - N)*((lint)sa[i - 1] - N) < 0)//如果sa[i]与sa[i - 1]来自不同的串 { start = sa[i]; return true; } } return false; } int main() { scanf("%d", &N); scanf("%s", tmp); for(int i = 0; i < N; i++) s[i] = tmp[i] - 'A' + 1; s[N] = 27; scanf("%s", tmp); for(int i = 0; i < N; i++) s[i + 1 + N] = tmp[i] - 'A' + 1; s[2*N + 1] = 0; da(s, sa, 2*N + 1 + 1, 30); calheight(s, sa, 2*N + 1); int L = 1, R = N, mid, ans = 0; //二分可能的长度, 因为如果长度len可行那么比len小的都可以,具有单调性 while(L <= R) { mid = (L + R) >> 1; if(check(mid, 2*N + 1)) { ans = mid; L = mid + 1; } else R = mid - 1; } for(int i = 0; i < ans; i++) printf("%c", s[start + i] + 'A' - 1); return 0; }