HDU—— 1867 A + B for you again

来源:互联网 发布:一朝成名天下知出处 编辑:程序博客网 时间:2024/06/05 06:39

题意:求两个字符串的并集。

解题思路:调用两次KMP,然后比较两次的匹配长度即可。

Code:

#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int N=100010;int f[N];void getFail(char *P){    int n = strlen(P);    int j=0,k=-1;    f[0]=-1;    while(j < n)    {        if(k >= 0 && P[j] != P[k]) k = f[k];        else { j++; k++; f[j] = k; }    }}int kmp(char *T,char *P){    int n = strlen(T), m = strlen(P);    getFail(P);    int i=0,j=0;    while(i<n)    {        if(j >= 0 && T[i] != P[j]) j = f[j];        else { i++; j++; }        if(j==m) break;//return i-wlen+1;    }    if(i == n) return j;//return -1;    else return 0;}int main(){    //freopen("input.txt","r",stdin);  char str1[N],str2[N];  while(scanf("%s%s",str1,str2)!=EOF)  {    int x=kmp(str1,str2);    int y=kmp(str2,str1);    if(x==y)    {        if(strcmp(str1,str2)>0)        {          printf("%s",str2);          printf("%s\n",str1+x);        }        else        {          printf("%s",str1);          printf("%s\n",str2+x);        }    }    else if(x>y)    {      printf("%s",str1);      printf("%s\n",str2+x);    }    else    {      printf("%s",str2);      printf("%s\n",str1+y);    }  }  return 0;}

0 0