NOJ [1380] 老蔡买水果 && [1180] Appreciate the Landscape
来源:互联网 发布:健身器材 知乎 编辑:程序博客网 时间:2024/05/22 00:38
这两题很类似,都是KMP的简单题,可怜的我今日才明白了next数组的含义,于是来尝试了下这两题
1380的代码
#include<stdio.h>#include<string.h>int next[400010];char S[400010],p[105];void get_next(){int i=0,j=-1;next[0]=-1;int len=strlen(p);while(i<len){if(j==-1 || p[i]==p[j]){i++;j++; next[i]=j;}else j=next[j];}}int KMP(){get_next();int i=0,j=0,count=0;int len=strlen(S);int m=strlen(p);while(i<len && j<m){if(j==-1 || S[i]==p[j]){i++;j++;}else j=next[j]; if(j==m) //模式串匹配到最后 那么成功匹配数++ { count++; j=next[j];//右移,靠上面的函数实现右移的距离 }}return count; }int main(){while(~scanf("%s%s",p,S)){int ans=KMP();printf("%d\n",ans);}return 0;}
附上我对next数组的理解
如果next[j]=-1;
说明有T[j]==T[0],而此时T与S失配,所以S[I]与T[0]已经间接比较过,所以不需要比,直接比S[i+1]与T[0]
如果next[j]=k;
说明有T[0.....k-1]==T[j-k....j-1],而此时j以前的字符,一定是成功匹配的,所以下一次的匹配就是s[i]与T[k]去比较
如果next[j]=0;
排除上述情况外,如果遇到失配,则要去比较S[i]和T[0]
0 0
- NOJ [1380] 老蔡买水果 && [1180] Appreciate the Landscape
- The Software-Quality Landscape
- Analysis of the NoSQL landscape
- Converting the app to landscape
- appreciate themselves
- the running man 【NOJ】
- A View of the Parallel Computing Landscape
- [NOJ 1137] The Running Man
- NOJ--1137--The Running Man
- NOJ [1186] Get the Width
- NOJ [1374] Find The Law
- NOJ [1251] Find the Palindrome
- NOJ [1306] Divide The Apples
- NOJ [1285] The TT Candy
- NOJ [1296] Between The Island
- NOJ 1137 The Running Man
- NOJ 1127 Kill the Zombies
- NOJ-1380(KMP)
- 云计算的三种服务模式
- char ** a; const char ** b; char * const * c; const char * const * d; const char * const * const e;对
- QlikView实现部分加载数据的功能(Partial Load)
- KL距离,Kullback-Leibler Divergence
- jQuery源码学习笔记:jQuery.fn.init(selector,context,rootjQuery)代码详解
- NOJ [1380] 老蔡买水果 && [1180] Appreciate the Landscape
- C++Primer笔记3(第四章-数组和指针)
- 在O(1)时间删除链表结点
- 【6】自己写数据库函数库 — 存储记录
- C++ Primer笔记4_类的静态成员_IO库
- Eclipse+Tomcat+Jersey 编写 REST web service
- Valid Palindrome
- 重构改善既有代码的设计--在对象之间搬移特性
- 分析jrtplib库的内存管理类