KMP(http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2772)
2014-06-17 18:37
441 查看
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char a[1000001],b[1000001];
int next[1000001];
int l,l2;
void Getnext()
{
int i=0;
int j=-1;
next[0]=-1;
while(i<l2)
{
if(-1==j||b[i]==b[j])
{
i++;
j++;
next[i]=j;
}
else j=next[j];
}
}
int main()
{
while(scanf("%s",a)!=EOF)
{
scanf("%*c%s",b);
l=strlen(a);
l2=strlen(b);
Getnext();
int i=0;
int j=0;
while(i<l&&j<l2)
{
if(a[i]==b[j]||j==-1)
{
i++;
j++;
}
else j=next[j];
}
if(j>=l2) printf("%d\n",i-l2+1);//判断条件
else printf("-1\n");
}
return 0;
}
#include <string.h>
#include <stdlib.h>
char a[1000001],b[1000001];
int next[1000001];
int l,l2;
void Getnext()
{
int i=0;
int j=-1;
next[0]=-1;
while(i<l2)
{
if(-1==j||b[i]==b[j])
{
i++;
j++;
next[i]=j;
}
else j=next[j];
}
}
int main()
{
while(scanf("%s",a)!=EOF)
{
scanf("%*c%s",b);
l=strlen(a);
l2=strlen(b);
Getnext();
int i=0;
int j=0;
while(i<l&&j<l2)
{
if(a[i]==b[j]||j==-1)
{
i++;
j++;
}
else j=next[j];
}
if(j>=l2) printf("%d\n",i-l2+1);//判断条件
else printf("-1\n");
}
return 0;
}
相关文章推荐
- http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2633
- http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2467&cid=1131
- http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2502&cid=1122
- SDUT 选夫婿1 http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=1569&cid=1211
- 站站排(重温儿时的游戏) http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=1573&cid=1211
- http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2500&cid=1122
- http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2504&cid=1122
- 站站排(重温儿时的游戏) http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=1573&cid=1211
- http://acm.hdu.edu.cn/webcontest/contest_showproblem.php?cid=963&pid=1019&ojid=1
- http://acm.hdu.edu.cn/webcontest/contest_showproblem.php?pid=1004&ojid=1&cid=6866&hide=1&problem=Pro
- 站站排(重温儿时的游戏) http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=1573&cid=1211
- http://acm.hdu.edu.cn/webcontest/contest_showproblem.php?cid=791&pid=1001&ojid=0
- Number Sequence&&http://acm.hdu.edu.cn/showproblem.php?pid=1005
- http://acm.hdu.edu.cn/showproblem.php?pid=1892&&二维树状数组
- 找规律。。&&http://acm.hdu.edu.cn/showproblem.php?pid=1097
- 导弹拦截二&&http://acm.hdu.edu.cn/showproblem.php?pid=1257
- Substrings &&http://acm.hdu.edu.cn/showproblem.php?pid=1238
- 树状数组&&http://acm.hdu.edu.cn/showproblem.php?pid=1556
- Max Sum &&http://acm.hdu.edu.cn/showproblem.php?pid=1003
- 最大连续子序列&&http://acm.hdu.edu.cn/showproblem.php?pid=1231