POJ 3080 后缀数组/KMP
题目链接:http://poj.org/problem?id=3080
题意:给定n个DNA串,求最长公共子串。如果最长公共子串的长度小于3时输出no significant commonalities,否则输出该子串,如有多解请输出字典序最小的解
思路:是POJ 3405的弱化版。思路请参考
#define _CRT_SECURE_NO_DEPRECATE #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<string> #include<queue> #include<vector> #include<time.h> #include<cmath> #include<set> using namespace std; typedef long long int LL; const int MAXN = 1000 + 10; 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 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) { 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], sa[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 r[MAXN], len, n, t, Index[MAXN], pos[60 + 5]; char str[60 + 5]; bool check(int x){ set<int>se; for (int i = 1; i < len; i++){ if (height[i] >= x){ pos[x] = sa[i]; se.insert(Index[sa[i]]); se.insert(Index[sa[i - 1]]); } else{ if (se.size() == n){ return true; } se.clear(); } } if (se.size() == n){ return true; } return false; } void solve(){ if (n == 1){ printf("%d\n", strlen(str)); return; } int L = 1, R = 60, mid, ans = 0; while (R >= L){ mid = (L + R) / 2; if (check(mid)){ ans = mid; L = mid + 1; } else{ R = mid - 1; } } if (ans <3){ printf("no significant commonalities\n"); } else{ for (int i = pos[ans], j = 0; j < ans; j++, i++){ printf("%c", (r[i] - n - 1) + 'A'); } printf("\n"); } } int main(){ //#ifdef kirito // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); //#endif // int start = clock(); scanf("%d", &t); while (t--){ scanf("%d", &n); len = 0; for (int i = 1, val = 0; i <= n; i++){ scanf("%s", &str); for (int j = 0; j < strlen(str); j++){ Index[len] = i; r[len++] = (str[j] - 'A' + n + 1); } Index[len] = i; r[len++] = val++; } da(r, sa, len, 100); calheight(r, sa, len - 1); solve(); } //#ifdef LOCAL_TIME // cout << "[Finished in " << clock() - start << " ms]" << endl; //#endif return 0; }