Blue Jeans
Description The Genographic Project is a research partnership between IBM and The National Geographic Society that is analyzing DNA from hundreds of thousands of contributors to map how the Earth was populated. Input Input to this problem will begin with a line containing a single integer n indicating the number of datasets. Each dataset consists of the following components:
Output For each dataset in the input, output the longest base subsequence common to all of the given base sequences. If the longest common subsequence is less than three bases in length, display the string "no significant commonalities" instead. If multiple subsequences of the same longest length exist, output only the subsequence that comes first in alphabetical order. Sample Input 3 2 GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 3 GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA GATACTAGATACTAGATACTAGATACTAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA GATACCAGATACCAGATACCAGATACCAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA 3 CATCATCATCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC ACATCATCATAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AACATCATCATTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT Sample Output no significant commonalities AGATAC CATCATCAT Source |
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char ch[15][70];
int nx[70];
char ch2[70], ans[70];
void cal_next(char b[], int m)
{
nx[0] = -1;
int k = -1;
for (int i = 1; i < m; i++)
{
while (k > -1 && b[k + 1] != b[i])
k = nx[k];
if (b[k + 1] == b[i])
k++;
nx[i] = k;
}
}
int KMP(char a[], char b[], int m)
{
cal_next(b, m);
int k = -1;
for (int i = 0; i < 60; i++)
{
while (k > -1 && b[k + 1] != a[i])
k = nx[k];
if (b[k + 1] == a[i])
k++;
if (k == m - 1)
return i - m + 2;
}
return -1;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("C:\\in.txt", "r", stdin);
#endif // ONLINE_JUDGE
int T;
scanf("%d", &T);
while (T--)
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%s", ch[i]);
int lans = -1;
int l = 3, r = 60;
while (l <= r)
{
int mid = (l + r) / 2;
bool Flag = 0;
for (int s = 0; s <= (59 - mid + 1) ; s++)
{
bool flag = 1;
for (int l = 0; l < mid; l++)
ch2[l] = ch[0][s + l];
ch2[mid] = '\0';
/// 从 ch[0] 中枚举取出长度为 mid 的字符串 存入 ch2
/// 检查其余串中是否包含 ch2[]
for (int i = 1; i < n; i++)
{
int temp = KMP(ch[i], ch2, mid);
if (temp == -1) // 有不包含的
flag = 0;
if (!flag)
break;
}
if (flag) // 都包含
{
if (mid > lans)
strcpy(ans, ch2);
else if (mid == lans && strcmp(ch2, ans) < 0) // ch2 < ans
strcpy(ans, ch2);
Flag = 1; // 当前mid长度可取
lans = mid;
}
}
if (Flag) // mid长度可取
l = mid + 1;
else
r = mid - 1;
}
if (lans == -1)
printf("no significant commonalities\n");
else
printf("%s\n", ans);
}
return 0;
}