zoukankan      html  css  js  c++  java
  • 【KMP模板】POJ3461-Oulipo

    【题意】

    找出第一个字符串在第二个字符串中出现次数。

    【注意点】

    一定要先将strlen存下来,而不能每次用每次求,否则会TLE!

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<algorithm>
     4 #include<cstring>
     5 using namespace std;
     6 const int MAXN=1000000+50;
     7 const int MAXM=10000+50; 
     8 char t[MAXN],p[MAXN];
     9 int next[MAXM];
    10 int lent,lenp;
    11 
    12 void getnext()
    13 {
    14     int i=0,j=-1;
    15     next[i]=j;
    16     while (i<lenp)
    17     {
    18         if (j==-1 || p[i]==p[j]) next[++i]=++j;
    19             else j=next[j];
    20     }
    21 }
    22 
    23 int getans()
    24 {
    25     int i=0,j=0,ans=0;
    26     while (i<lent)
    27     {
    28         if (t[i]==p[j] || j==-1)
    29         {
    30             i++;
    31             j++;
    32         }
    33         else j=next[j];
    34         if (j==lenp)//如果匹配成功,则视作这次匹配失败,返回到上一次。 
    35         {
    36             ans++;
    37             j=next[j-1];
    38             i--;
    39         }
    40     }
    41     return ans;
    42 }
    43 
    44 int main()
    45 {
    46     int kase;
    47     scanf("%d",&kase);
    48     for (int i=0;i<kase;i++)
    49     {
    50         scanf("%s%s",p,t);
    51         lent=strlen(t); 
    52         lenp=strlen(p);//注意一定要先把strlen存下来,否则会TLE! 
    53         getnext();
    54         cout<<getans()<<endl;
    55     }
    56     return 0;
    57 }
  • 相关阅读:
    PKU 3984 迷宫问题
    九度 1341 艾薇儿的演唱会
    九度 1335
    SDUT 1198 鞍点计算
    POJ 1363 Rails
    SDUT 1570 C旅行
    HDU 1042 N!
    SDUT 1568 俄罗斯方块
    HDU 1257 最少拦截系统
    POJ 3750 小孩报数问题
  • 原文地址:https://www.cnblogs.com/iiyiyi/p/5251326.html
Copyright © 2011-2022 走看看