zoukankan      html  css  js  c++  java
  • hdu1686Oulipo(KMP)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1686

    用KMP查找模式串在目标串中出现的次数。

     1 #include<cstdio>
     2 #include<cstring>
     3 char t[1001010],p[10100];
     4 int nex[10100];
     5 int tlen,plen;
     6 int ans;
     7 void getnex()
     8 {
     9     int j=0,k=-1;
    10     nex[0]=-1;
    11     while(j<plen)
    12     {
    13         if(k==-1||p[j]==p[k])
    14             nex[++j]=++k;
    15         else  k=nex[k];
    16     }
    17 }
    18 
    19 int KMP()
    20 {
    21     if(tlen==1&&1==plen)
    22     {
    23         if(t[0]==p[0]) return 1;
    24         else return 0;
    25     }
    26     getnex();
    27     int i=0,j=0;
    28     for(;i<tlen;i++)
    29     {
    30         while(j>0&&t[i]!=p[j])
    31             j=nex[j];
    32         if(t[i]==p[j]) j++;
    33         if(j==plen)
    34         {
    35             ans++;
    36             j=nex[j];
    37         }
    38     }
    39     return ans;
    40 }
    41 
    42 int main()
    43 {
    44     int tt;
    45     scanf("%d",&tt);
    46     while(tt--)
    47     {
    48         scanf("%s%s",p,t);
    49         ans=0;
    50         tlen=strlen(t);
    51         plen=strlen(p);
    52         printf("%d
    ",KMP());
    53 
    54     }
    55 }

    我的KMP模板(感觉这样统一比较好记)

     1 #include<cstdio>
     2 #include<cstring>
     3 const int maxn=1000010;
     4 int pl,sl;
     5 int nex[maxn];
     6 char s[maxn],p[maxn];
     7 int ans=0;
     8 void getnex(char *p)
     9 {
    10     int j=0,k=-1;
    11     nex[0]=-1;
    12     while(j<pl)
    13     {
    14         if(k==-1||p[j]==p[k])
    15             nex[++j]=++k;
    16         else k=nex[k];
    17     }
    18 }
    19 void KMP(char *s,char *p)
    20 {
    21     getnex(p);
    22     int i=0,j=0;
    23     while(i<sl)
    24     {
    25         if(j==-1||s[i]==p[j])
    26         {
    27             i++;
    28             j++;
    29         }
    30         else j=nex[j];
    31         if(j==pl)
    32         {
    33             ans++;
    34             j=nex[j];
    35         }
    36     }
    37 }
    38 int main()
    39 {
    40     int t;
    41     scanf("%d",&t);
    42     while(t--)
    43     {
    44         scanf("%s%s",p,s);
    45         sl=strlen(s);
    46         pl=strlen(p);
    47         ans=0;
    48         KMP(s,p);
    49         printf("%d
    ",ans);
    50     }
    51 }
    View Code
  • 相关阅读:
    【Leetcode】反转链表 II
    将博客搬至CSDN
    UVA 11021(概率)
    zoj
    Codeforces Round #227 (Div. 2) / 387C George and Number (贪心)
    点头(1163)
    fzu-2164 Jason's problem(数论)
    nyist --ACM组队练习赛(链接)
    nyoj-括号匹配(二)15---动态规划
    动态规划
  • 原文地址:https://www.cnblogs.com/yijiull/p/6613468.html
Copyright © 2011-2022 走看看