hdu 1686 Oulipo (kmp模板题)

hdu1686

题意:给出模式串和文本串,问模式串在文本串中出现了多少次,可以overlap.

思路:思考naive的匹配过程。nxt函数不过是改进了当失配发生时,不是移动1位,而是移动多位。nxt函数的含义是当失配发生时,移动到的位置….所以有的教程管这个叫失配函数吧,也不是很难理解的样子。

学会kmp之后的第一道kmp,嘿嘿嘿(是的,poj2406的时候我并不会kmp 2333)

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2016年08月10日 星期三 20时02分33秒
 4File Name :code/hdu/1686.cpp
 5************************************************ */
 6
 7#include <cstdio>
 8#include <cstring>
 9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <stack>
14#include <set>
15#include <map>
16#include <string>
17#include <cmath>
18#include <cstdlib>
19#include <deque>
20#include <ctime>
21#define fst first
22#define sec second
23#define lson l,m,rt<<1
24#define rson m+1,r,rt<<1|1
25#define ms(a,x) memset(a,x,sizeof(a))
26typedef long long LL;
27#define pi pair < int ,int >
28#define MP make_pair
29
30using namespace std;
31const double eps = 1E-8;
32const int dx4[4]={1,0,0,-1};
33const int dy4[4]={0,-1,1,0};
34const int inf = 0x3f3f3f3f;
35const int N=1E4+7;
36string a,b;
37int ans;
38int nxt[N];
39
40void getnxt( int n)
41{
42    int i = 0;
43    int j = -1;
44    nxt[0] = -1;
45    while (i<n)
46	if (j==-1||b[i]==b[j]) nxt[++i]=++j;
47    else j = nxt[j];
48}
49
50void kmp( int n,int m)
51{
52    int i = 0 ;
53    int j = 0 ;
54    getnxt(m);
55   // for ( int i = 0 ; i < m ; i++) cout<<i<<" "<<nxt[i]<<endl;
56    while (i<n)
57    {
58	if (j==-1||a[i]==b[j]) i++,j++;
59	else j = nxt[j];
60	if (j==m) ans++,j=nxt[j];
61
62//	cout<<"n:"<<n<<" i:"<<i<<" j:"<<j<<endl;
63    }
64}
65int main()
66{
67	#ifndef  ONLINE_JUDGE 
68	freopen("code/in.txt","r",stdin);
69  #endif
70
71	ios::sync_with_stdio(false);
72	int T;
73	cin>>T;
74	while (T--)
75	{
76	    cin>>a>>b;
77	    swap(a,b);
78//	    cout<<"a:"<<a<<" b:"<<b<<endl;
79	    int la = a.length();
80	    int lb = b.length();
81	    ans = 0 ;
82	    kmp(la,lb);
83	    cout<<ans<<endl;
84
85
86	}
87
88  #ifndef ONLINE_JUDGE  
89  fclose(stdin);
90  #endif
91    return 0;
92}