码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1711 Number Sequence

时间:2018-04-23 21:19:33      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:seq   display   enc   分享图片   splay   space   sequence   cout   color   

结题思路:KMP标准模板题,注意KMP有两个版本,这里的优劣在代码中已体现

技术分享图片
 1 #include <iostream>
 2 #include <cstring>
 3 #include <string>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 int a[1000100];
 8 int b[10100];
 9 int Len_a, Len_b;
10 int Next[10100];
11 void GetNext()
12 {
13     int i = 0, j = Next[0] = -1;
14     while (i < Len_b)
15     {
16         //Version 1
17         if (j == -1 || b[i] == b[j])
18             Next[++i] = ++j;
19         /* 
20              
21             Version 2:
22             if (j == -1 || b[i] == b[j])
23             {
24                 i++;
25                 j++;
26                 Next[i] = (b[i] == b[j] ? Next[j] : j)
27             }
28             改进的 next[] 表与不改进的 next[] 表相比,计算 next[] 表本身的时间慢一点,但 KMP 匹配的时候跳转的平均长度稍大一点。
29 
30             构造后一个 next[] 表只用一次体现不出优势。如果一个模式串要与很多个字符串匹配, 改进的 next[] 构造时间微不足道,匹配的速度就体现出来了。
31             题型匹配:HDU-1686 Oulipo 
32         */
33         else
34             j = Next[j];
35     }
36 }
37 
38 int KMP()
39 {
40     int i = 0, j = 0;
41     GetNext();
42     while (i < Len_a && j < Len_b)
43     {
44         if (j == -1 || a[i] == b[j])
45         {
46             i++;
47             j++;
48         }
49         else
50             j = Next[j];
51     }
52     
53     if (j == Len_b)
54         return i - j + 1;
55     else
56         return -1;
57 }
58 
59 int main(void)
60 {
61     ios::sync_with_stdio(false);
62     
63     int cas;
64     cin >> cas;
65     while (cas--)
66     {
67         cin >> Len_a >> Len_b;
68         for (int i = 0; i < Len_a; ++i)
69             cin >> a[i];
70             
71         for (int j = 0; j < Len_b; ++j)
72             cin >> b[j];    
73             
74         cout << KMP() << endl;
75     }
76     
77     return 0;
78 }
View Code

 

HDU 1711 Number Sequence

标签:seq   display   enc   分享图片   splay   space   sequence   cout   color   

原文地址:https://www.cnblogs.com/ducklu/p/8921726.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!