hdu 1686 Oulipo (kmp模板题)

hdu1686

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

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

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

/* ***********************************************
Author :111qqz
Created Time :2016年08月10日 星期三 20时02分33秒
File Name :code/hdu/1686.cpp
************************************************ */
 1#include <cstdio>
 2#include <cstring>
 3#include <iostream>
 4#include <algorithm>
 5#include <vector>
 6#include <queue>
 7#include <stack>
 8#include <set>
 9#include <map>
10#include <string>
11#include <cmath>
12#include <cstdlib>
13#include <deque>
14#include <ctime>
15#define fst first
16#define sec second
17#define lson l,m,rt<<1
18#define rson m+1,r,rt<<1|1
19#define ms(a,x) memset(a,x,sizeof(a))
20typedef long long LL;
21#define pi pair < int ,int >
22#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N=1E4+7;
7string a,b;
8int ans;
9int nxt[N];
1void getnxt( int n)
2{
3    int i = 0;
4    int j = -1;
5    nxt[0] = -1;
6    while (i<n)
7	if (j==-1||b[i]==b[j]) nxt[++i]=++j;
8    else j = nxt[j];
9}
 1void kmp( int n,int m)
 2{
 3    int i = 0 ;
 4    int j = 0 ;
 5    getnxt(m);
 6   // for ( int i = 0 ; i < m ; i++) cout<<i<<" "<<nxt[i]<<endl;
 7    while (i<n)
 8    {
 9	if (j==-1||a[i]==b[j]) i++,j++;
10	else j = nxt[j];
11	if (j==m) ans++,j=nxt[j];
1//	cout<<"n:"<<n<<" i:"<<i<<" j:"<<j<<endl;
2    }
3}
4int main()
5{
6	#ifndef  ONLINE_JUDGE 
7	freopen("code/in.txt","r",stdin);
8  #endif
 1	ios::sync_with_stdio(false);
 2	int T;
 3	cin>>T;
 4	while (T--)
 5	{
 6	    cin>>a>>b;
 7	    swap(a,b);
 8//	    cout<<"a:"<<a<<" b:"<<b<<endl;
 9	    int la = a.length();
10	    int lb = b.length();
11	    ans = 0 ;
12	    kmp(la,lb);
13	    cout<<ans<<endl;
	}
1  #ifndef ONLINE_JUDGE  
2  fclose(stdin);
3  #endif
4    return 0;
5}