KMP
2015-12-07 21:22
357 查看
KMP的核心就是next数组,next[j]存储的就是0~j-1的字符串前后缀最长长度.
老实说,这个部分真心难,我也只是大概弄懂,套套版,等放假要搞搞清楚。
poj3461
#include <stdio.h>
#include <string.h>
int next[1000100];
char p[1000100];
char s[1000100];
int l1;
int l2;
int ans;
void GetNext()
{
int i=0;
int j=-1;
next[0]=-1;
while(i<l1)
{
if ((j==-1)||(p[i]==p[j]))
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
void KMP()
{
int i=0;
int j=0;
while(i<l1&&j<l2)
{
if ((s[i]==p[j])||(j==-1))
{
i++;
j++;
}
else
j=next[j];
if (j==l2)//原来是一旦找到第一个符合,就退出循环
{
ans++;
j=next[j];
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%s%s",p,s);
l1=strlen(s);
l2=strlen(p);
ans=0;
GetNext();
KMP();
printf("%d\n",ans);
}
return 0;
}
poj2406最后有点....
#include <stdio.h>
#include <string.h>
char s[1000010];
int next[1000010];
int l;
int ls;
void GetNext()
{
int i,j;
i=0;
j=-1;
next[0]=-1;
while(i<ls)
{
if ((j==-1)||(s[i]==s[j]))
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int main()
{
while(scanf("%s",s)&&(s[0]!='.'))
{
ls=strlen(s);
GetNext();
l=ls-next[ls];
if ((l!=ls)&&(ls%l==0))
printf("%d\n",ls/l);
else
printf("1\n");
}
return 0;
}
老实说,这个部分真心难,我也只是大概弄懂,套套版,等放假要搞搞清楚。
poj3461
#include <stdio.h>
#include <string.h>
int next[1000100];
char p[1000100];
char s[1000100];
int l1;
int l2;
int ans;
void GetNext()
{
int i=0;
int j=-1;
next[0]=-1;
while(i<l1)
{
if ((j==-1)||(p[i]==p[j]))
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
void KMP()
{
int i=0;
int j=0;
while(i<l1&&j<l2)
{
if ((s[i]==p[j])||(j==-1))
{
i++;
j++;
}
else
j=next[j];
if (j==l2)//原来是一旦找到第一个符合,就退出循环
{
ans++;
j=next[j];
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%s%s",p,s);
l1=strlen(s);
l2=strlen(p);
ans=0;
GetNext();
KMP();
printf("%d\n",ans);
}
return 0;
}
poj2406最后有点....
#include <stdio.h>
#include <string.h>
char s[1000010];
int next[1000010];
int l;
int ls;
void GetNext()
{
int i,j;
i=0;
j=-1;
next[0]=-1;
while(i<ls)
{
if ((j==-1)||(s[i]==s[j]))
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int main()
{
while(scanf("%s",s)&&(s[0]!='.'))
{
ls=strlen(s);
GetNext();
l=ls-next[ls];
if ((l!=ls)&&(ls%l==0))
printf("%d\n",ls/l);
else
printf("1\n");
}
return 0;
}
相关文章推荐
- 【Java基础】Java多线程小结
- JavaScript 语法总结
- cc2530裸机编程系列笔记6--外中断程序(转载)
- 同余定理在编程中的应用
- Block 的 基础 封装方法中遇到的block问题
- sscanf 编
- MFC DLL获取当前路径
- 预处理、const、static与sizeof
- 如何清除xcode里面的mobileprovision文件
- 读书笔记 -- 001_数据预处理_数据清理
- 递归求解并生成哈夫曼编码的代码实现
- Android消息机制 Handler源码分析
- PAT 1014 福尔摩斯的约会
- POJ2481 Cows 树状数组
- 用python 10min手写一个简易的实时内存监控系统
- python语法笔记(二)
- 三分搜索法
- 3116 高精度练习之加法
- 鸡蛋队列
- 关于VB选择打印机,并打印