hdu 2594 Simpsons’ Hidden Talent (kmp)

hdu 2594 题目链接

题意:given string s1,s2, find the longest prefix of s1 that is a suffix of s2.

思路:kmp。。。懒得说了。注意边界。

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2016年08月12日 星期五 01时12分51秒
 4File Name :code/hdu/2594.cpp
 5************************************************ */
 6#include <cstdio>
 7#include <cstring>
 8#include <iostream>
 9#include <algorithm>
10#include <vector>
11#include <queue>
12#include <stack>
13#include <set>
14#include <map>
15#include <string>
16#include <cmath>
17#include <cstdlib>
18#include <deque>
19#include <ctime>
20#define fst first
21#define sec second
22#define lson l,m,rt<<1
23#define rson m+1,r,rt<<1|1
24#define ms(a,x) memset(a,x,sizeof(a))
25typedef long long LL;
26#define pi pair < int ,int >
27#define MP make_pair
28using namespace std;
29const double eps = 1E-8;
30const int dx4[4]={1,0,0,-1};
31const int dy4[4]={0,-1,1,0};
32const int inf = 0x3f3f3f3f;
33const int N=5E5+7;
34char a[N],b[N];
35int nxt[N];
36void getnxt( char *s)
37{
38    int n = strlen(s);
39    int i = 0 ;
40    int j = -1;
41    nxt[0] = -1;
42    while (i<n)
43	if (j==-1||s[i]==s[j]) nxt[++i]=++j;
44	else j = nxt[j];
45}
46int kmp(char *a,char *b)
47{
48    int n = strlen(a);
49    int m = strlen(b);
50    getnxt(b);
51    int i = 0;
52    int j = 0;
53    while (i<n)
54    {
55	if (j==-1||a[i]==b[j]) i++,j++;
56	else j = nxt[j];
57    }
58    if (i==n) return j;
59    return 0;
60}
61int main()
62{
63	#ifndef  ONLINE_JUDGE 
64	freopen("code/in.txt","r",stdin);
65  #endif
66	while (~scanf("%s %s",a,b))
67	{
68//	    cout<<"a:"<<a<<" b:"<<b<<endl;
69	    int k = kmp(b,a);
70	    if (k==0)
71		puts("0");
72	    else printf("%s %d\n",b+(strlen(b)-k),k);
1	    ms(a,0);
2	    ms(b,0);
3	}
4  #ifndef ONLINE_JUDGE  
5  fclose(stdin);
6  #endif
7    return 0;
8}