• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
若忆_star
博客园    首页    新随笔    联系   管理    订阅  订阅
hdu 1711 Number Sequence

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

题目大意:在母链中找到子链的位置,输出开始的位置。

 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 int lens,lenc,next[1000005],str[1000005],ch[1000005];
 5 
 6 int get_next()
 7 {
 8     int i=0,j=-1;
 9     next[0]=-1;
10     while (i<lens)
11     {
12         if (j==-1||str[i]==str[j])
13         {
14             i++;
15             j++;
16             next[i]=j;
17         }
18         else
19             j=next[j];
20     }
21 }
22 
23 int kmp()
24 {
25     int i=0,j=0;
26     get_next();
27     while (i<lenc)
28     {
29         if(j==-1||str[j]==ch[i])
30         {
31             i++;
32             j++;
33         }
34         else
35             j=next[j];
36         if (j==lens)
37             return i-j+1;
38 
39     }
40     return -1;
41 }
42 
43 int main ()
44 {
45     int t;
46     scanf("%d",&t);
47     while (t--)
48     {
49         //int n,m;
50         scanf("%d%d",&lenc,&lens);
51         for (int i=0; i<lenc; i++)
52             scanf("%d",&ch[i]);
53         for (int j=0; j<lens; j++)
54             scanf("%d",&str[j]);
55         printf ("%d\n",kmp());
56     }
57     return 0;
58 }

 

posted on 2014-08-04 19:56  若忆_star  阅读(440)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3