zoukankan      html  css  js  c++  java
  • Oulipo

    poj3461:http://poj.org/problem?id=3461

    题意:求一个串在另一个串中出现的次数。

    题解:直接套用KMP即可,在统计的时候做一下修改。找到之后不是直接返回,而是移动i-(j-next[j])位。

     1 #include<cstdio>
     2 #include<cstdlib>
     3 #include<cstring>
     4 #define N 1000005
     5 using namespace std;
     6 int next[N];
     7 char s1[N],s2[N];
     8 int len1,len2,ans;
     9 void getnext(int plen){
    10     int i = 0,j = -1;
    11     next[0] = -1;
    12     while( i<plen ){
    13         if(j==-1||s1[i]==s1[j]){
    14             ++i;++j;
    15           if(s1[i]!=s1[j] )
    16             next[i] = j;
    17           else
    18             next[i] = next[j];
    19         }
    20         else
    21             j = next[j];
    22     }
    23 }
    24 void KMP(){
    25     getnext(len1);
    26     int i = 0,j = 0;
    27     while (i<len2&&j<len1){
    28         if( j == -1 || s2[i] == s1[j] ){
    29             ++i;
    30             ++j;
    31         }
    32         else {
    33             j = next[j];
    34 
    35         }
    36          if( j==len1 ){//找到一个匹配串之后,不是在原来串中往后移动一位,而是移动i-(j-next[j]);
    37             ans++;
    38             j=next[j];
    39          }
    40     }
    41 }
    42 int main(){
    43     int k;
    44     scanf("%d",&k);
    45     while(k--){
    46         scanf("%s%s",s1,s2);
    47         len1=strlen(s1);
    48         len2=strlen(s2);
    49         ans=0;
    50         KMP();
    51         printf("%d
    ",ans);
    52     }
    53 }
    View Code
  • 相关阅读:
    求1+2+3+...+n
    孩子们的游戏(圆圈中最后剩下的数) 约瑟夫环
    扑克牌顺子
    翻转单词顺序列
    左旋转字符串
    和为S的两个数字
    和为S的连续正数序列
    CocoaPods 更新
    UITextView 动态高度计算(iOS7版)
    Mac 把图片反色
  • 原文地址:https://www.cnblogs.com/chujian123/p/3855085.html
Copyright © 2011-2022 走看看