题目链接:http://poj.org/problem?id=3080
题目大意:给定m个串,求长度大等于3且在每个串中都出现的最长子串,如果两个子串长度一样要求输出字典序小的一个答案。如果没有则输出“no significant commonalities".
解题思路:第枚举第一串的所有大等于3的子串,再与其他每个串进行匹配,如果能匹配到则更新答案。
测试数据:
5
2
ACTACTACTACT
ACTACTACTACT
3
ABCABC
ABCA
ABCAA
2
GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
3
GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATA
GATACTAGATACTAGATACTAGATACTAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA
GATACCAGATACCAGATACCAGATACCAAAGGAAAGGGAAAAGGGGAAAAAGGGGGAAAA
3
CATCATCATCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
ACATCATCATAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AACATCATCATTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
代码:
#include <stdio.h>
#include <string.h>
int Kmp(char *s1,char *s2) {
int next[100];
int i,j,k,len1,len2;
len1 = strlen(s1);
len2 = strlen(s2);
i = 0,j = -1;
next[0] = -1;
while (i < len2) {
if (j == -1 || s2[i] == s2[j])
i++,j++,next[i] = j;
else j = next[j];
}
i = j = 0;
while (i < len1) {
if (j == -1 || s1[i] == s2[j])
i++,j++;
else j = next[j];
if (j == len2) return 1;
}
return 0;
}
int main()
{
int i,j,k,t,m,flag,stlen,len;
char str[11][100],ans[100],tp[100];
scanf("%d",&t);
while (t--) {
scanf("%d",&m);
for (i = 0; i < m; ++i)
scanf("%s",str[i]);
ans[0] = '\0';
stlen = strlen(str[0]); //枚举第一个串中长度大于3的子串
for (len = 3; len <= stlen; ++len)
for (i = 0; i <= stlen - len; ++i) {
for (k = 0,j = i; j < i + len; ++j)
tp[k++] = str[0][j];
tp[k] = '\0';
for (k = 1; k < m; ++k)
if (Kmp(str[k],tp) == 0) break;
if (k == m) {
if (strlen(ans) == len && strcmp(ans,tp) > 0)
strcpy(ans,tp);
if (strlen(ans) < len) strcpy(ans,tp);
}
}
if (ans[0] == '\0')
printf("no significant commonalities\n");
else printf("%s\n",ans);
}
}
本文章为ZeroClock原创,但可以转载,因为我们是兄弟。