zoukankan      html  css  js  c++  java
  • POJ3461 KMP简单变形输出模式串在主串出现的次数

    题目链接:http://poj.org/problem?id=3461

    大概意思就是标题那个意思,给样例数,给模式串,给主串,求模式串在主串出现的次数。数据量大,所以要用到KMP,然后简单变形下

    #include<iostream>
    #include<cstring>
    #include<cstdio>
    using namespace std;
    
    char T[1000005],P[10005];
    
    int next[10010],tn,pn,Case;
    void Makenext(int tn){
        int i=0,j=-1;
        next[0] = -1;
        while(i<tn){
            if(j==-1||P[i]==P[j])
                next[++i] = ++j;
            else j = next[j];
        }
    }
    int KMP(int pos,int N,int M){
        int i = pos, j = 0,ans = 0;
        while(i<N){
            if(T[i]==P[j]||j==-1)i++,j++;
            else j = next[j];
            //KMP变形核心部分//
            if(j==M){
                ans++;
                j = next[j-1];//这里用到的就是KMP笔记第二页开始的i和j移动规律以及next数组里面存放的意义
                i--;//可能与next[0]和上面i++有关
            }
        }
        return ans;
    }
    int main(){
        scanf("%d",&Case);
        while(Case--){
            scanf("%s%s",P,T);
            tn = strlen(T),pn = strlen(P);
            Makenext(pn);
            printf("%d
    ",KMP(0,tn,pn));
        }
        return 0;
    }
    

    然后对于KMP的理解:



  • 相关阅读:
    原型污染
    C#之抛异常
    为什么['1', '7', '11'].map(parseInt) returns [1, NaN, 3]?
    Linux
    Linux
    Linux
    Linux
    Linux
    Linux
    其他
  • 原文地址:https://www.cnblogs.com/zhangmingzhao/p/7256723.html
Copyright © 2011-2022 走看看