hdu1841 kmp(用最短的串使包含存在的两个串)

1.大的包含小的,求kmp即可

2.一个串的前缀是另一个串的后缀,合并利用next数组

 1 #include<stdio.h>
 2 #include<string.h>
 3 char s1[1000005],s2[1000005],t1[1000005],t2[1000005];
 4 char s[2000005];
 5 int next[2000005];
 6 int find(char *A,char *B,int n,int m)
 7 {
 8   int i,j=0;
 9   for (i=1;i<=n;i++)
10   {
11     while (j>0&&B[j+1]!=A[i]) j=next[j];
12     if (B[j+1]==A[i]) j++;
13     if (j==m) return i-m+1;
14   }
15   return -1;
16 }
17 void getnext(char *B,int m)
18 {
19   int i,j;
20   next[1]=j=0;
21   for (i=2;i<=m;i++)
22   {
23     while (j>0&&B[j+1]!=B[i]) j=next[j];
24     if (B[j+1]==B[i]) j++;
25     next[i]=j;
26   }
27 }
28 int main()
29 {
30   int T,len1,len2,n,tmp,i,minx;
31   scanf("%d",&T);
32   while (T--)
33   {
34     scanf("%s%s",s1,s2);
35     len1=strlen(s1); len2=strlen(s2);
36     n=len1+len2;
37     if (len1<len2){
38       tmp=len1; len1=len2; len2=tmp;
39       strcpy(s,s1); strcpy(s1,s2); strcpy(s2,s);
40     }
41     for (i=len1;i>=1;i--) t1[i]=s1[i-1];
42     for (i=len2;i>=1;i--) t2[i]=s2[i-1];
43     getnext(t2,len2);
44     if (find(t1,t2,len1,len2)>0) {printf("%d\n",len1);continue;}
45       strcpy(s,s1); strcat(s,s2);
46     for (i=n;i>=1;i--) s[i]=s[i-1];
47     getnext(s,n); tmp=n;
48     while (next[tmp]>0&&next[tmp]>len2) tmp=next[tmp];
49     minx=n-next[tmp];
50     strcpy(s,s2); strcat(s,s1);
51     for (i=n;i>=1;i--) s[i]=s[i-1];
52     getnext(s,n); tmp=n;
53     while (next[tmp]>0&&next[tmp]>len2) tmp=next[tmp];
54     if (n-next[tmp]<minx) minx=n-next[tmp];
55     printf("%d\n",minx);
56   }
57 }
View Code

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1841

posted on 2015-02-02 02:38  xiao_xin  阅读(79)  评论(0编辑  收藏  举报

导航