【C++】henuACM暑期培训Day11 KMP

写题解前,先放出来一个大神的关于KMP的博客https://blog.csdn.net/v_july_v/article/details/7041827
说真的,昨天学长说今天讲的KMP会有点难,但是跟着听也能理解。果不其然,我中间玩了会QQ,就不会了= = 花了一下午时间去理解,最终明白了三四,但对于非模板题,还是需要一遍又一遍的去更好的理解KMP。

A题 Oulipo

The French author Georges Perec (1936–1982) once wrote a book, La disparition, without the letter ‘e’. He was a member of the Oulipo group. A quote from the book:
Tout avait Pair normal, mais tout s’affirmait faux. Tout avait Fair normal, d’abord, puis surgissait l’inhumain, l’affolant. Il aurait voulu savoir où s’articulait l’association qui l’unissait au roman : stir son tapis, assaillant à tout instant son imagination, l’intuition d’un tabou, la vision d’un mal obscur, d’un quoi vacant, d’un non-dit : la vision, l’avision d’un oubli commandant tout, où s’abolissait la raison : tout avait l’air normal mais…
Perec would probably have scored high (or rather, low) in the following contest. People are asked to write a perhaps even meaningful text on some subject with as few occurrences of a given “word” as possible. Our task is to provide the jury with a program that counts these occurrences, in order to obtain a ranking of the competitors. These competitors often write very long texts with nonsense meaning; a sequence of 500,000 consecutive 'T’s is not unusual. And they never use spaces.
So we want to quickly find out how often a word, i.e., a given string, occurs in a text. More formally: given the alphabet {‘A’, ‘B’, ‘C’, …, ‘Z’} and two finite strings over that alphabet, a word W and a text T, count the number of occurrences of W in T. All the consecutive characters of W must exactly match consecutive characters of T. Occurrences may overlap.

Input

The first line of the input file contains a single number: the number of test cases to follow. Each test case has the following format:

  • One line with the word W, a string over {‘A’, ‘B’, ‘C’, …, ‘Z’}, with 1 ≤ |W| ≤ 10,000 (here |W| denotes the length of the string W).
  • One line with the text T, a string over {‘A’, ‘B’, ‘C’, …, ‘Z’}, with |W| ≤ |T| ≤ 1,000,000.

Output

For every test case in the input file, the output should contain a single number, on a single line: the number of occurrences of the word W in the text T.

Sample Input

3
BAPC
BAPC
AZA
AZAZAZA
VERDI
AVERDXIVYERDIAN

Sample Output

1
3
0

题意: 就是给一个字符串,然后给个目标字符串,求这个目标在长的那个字符串里面出现了几次

思路: 本人理解,所谓KMP,就是在暴力匹配的基础上,将每次匹配失败后进行下一匹配的位置进行优化,暴力匹配是每次往右移动一位,但这样会浪费很多时间在匹配过的点上。而KMP中引入了一个next数组,通过目标字符串的相同前缀后缀求出来其next数组,失配时,模式串向右移动的位数为:失配字符所在位置 - 失配字符对应的next 值。

求next数组的模板
有时候也把k初始化为0,j为1

void getnext(int len) 
{ 
    int j, k; 
    j = 0; k = -1; //初始化值为-1且下标从0开始
    next[0] = -1; 
    while(j < len) 
{ 
    if(k == -1 || b[j] == b[k]) 
    { 
        j++; k++; 
        next[j] = k; 
    } 
    else k = next[k]; } } 

KMP模板

int kmp(int len1, int len2) 
{ 
    int i, j; 
    int cnt = 0; 
    i = 0; j = 0; 
    getnext(len2); //得到目标串的next数组 
    while(i < len1) 
    { 
        if(j == -1 || a[i] == b[j]) 
        { 
            i++; j++; 
        } 
        else j = next[j]; 
        if(j == len2) cnt++; //记录目标串出现的次数 
    } 
    return cnt; 
} 

完整AC代码

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
const int maxx = 1e6+10;
char s1[maxx],s2[maxx];

int nextt[maxx];

void getnext(int len)
{
    int j,k;
    j=0;k=-1;
    nextt[0] = -1;
    while(j<len)
    {
        if(k == -1 || s2[k] == s2[j]){
            ++k;++j;
            nextt[j] = k;
        }
        else{k = nextt[k];}
    }
}

int kmp(int len1,int len2)
{
    int i=0;int j=0;int ans=0;
    getnext(len2);
    while(i<len1)
    {
        if(j == -1 || s1[i] == s2[j])
        {
            ++i;++j;
        }
        else{j = nextt[j];}
        if(j==len2){ans++;}
    }
    return ans;
}

int main()
{
    int n;
    scanf("%d",&n);
    //cin>>n;
    while(n--)
    {
        scanf("%s%s",s2,s1);
        //cin>>s2>>s1;
        int len1 = strlen(s1);
        int len2 = strlen(s2);
        printf("%d\n",kmp(len1,len2));
        //cout<<kmp(len1,len2)<<endl;
    }
    return 0;
}

注:

  1. cin cout会超时,需要用到scanf和printf,但是c语言的输入输出是不能直接对string类进行操作,方法以后再去学,这里暂时先把string换成了char。

  2. 求char类型长度用strlen()
    求string类型长度用str.length()

  3. next可能会在vj上报错,改成nextt。

猜你喜欢

转载自blog.csdn.net/qq_44899247/article/details/97276323
kmp