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

KMP

时间:2018-10-19 21:54:30      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:cstring   namespace   ons   begin   out   hide   mes   题意   math   

Codeforces 607C:Marbles

题意:

由“NSWE”表示上下左右。然后有两个球在各自坑道的起点。之后由你对两个小球做相同的操作,想让小球往上走就往上走,想往下走就往下走。但是要保证两个小球保持一致的动作,其中一个撞墙的话不用管。问能不能保证两个小球都能从起点到达终点。

solution:

trans+KMP

技术分享图片
 1 #pragma warning(disable:4996)  
 2 #include <iostream>  
 3 #include <algorithm>  
 4 #include <cmath>  
 5 #include <vector>  
 6 #include <string>  
 7 #include <cstring>
 8 #include <queue>
 9 #include <map>
10 using namespace std;
11 typedef long long ll;
12  
13 #define INF 0x3fffffff
14  
15 const int maxn = 2e6 + 5;
16  
17 int n, len;
18 int nex[maxn];
19 string a, b;
20 string all;
21  
22 char trans(char x)
23 {
24     if (x == N)
25     {
26         return S;
27     }
28     else if (x == S)
29     {
30         return N;
31     }
32     else if (x == W)
33     {
34         return E;
35     }
36     else if (x == E)
37     {
38         return W;
39     }
40 }
41  
42 void kmp(string s)
43 {    
44     int i, j;
45     len = s.length();
46  
47     nex[0] = -1;
48     j = -1;
49     for (i = 1; i < len; i++)
50     {
51         while (j != -1 && s[i] != s[j + 1])
52         {
53             j = nex[j];
54         }
55         if (s[i] == s[j + 1])
56             j++;
57         nex[i] = j;
58     }
59 }
60  
61 void input()
62 {
63     cin >> n >> a >> b;
64 }
65  
66 void solve()
67 {
68     n--;
69     
70     reverse(b.begin(), b.end());
71     for(char &c : b)
72         c = trans(c);
73     all = b +   + a;
74     cout<<all<<endl;
75     kmp(all);
76     cout<<endl<<nex[len-1]<<endl; 
77     puts(nex[len - 1] == -1 ? "YES" : "NO");
78  
79 }
80  
81 int main()
82 {
83     //freopen("i.txt", "r", stdin);
84     //freopen("o.txt", "w", stdout);
85  
86     input();
87     solve();
88  
89     //system("pause");
90     return 0;
91 }
View Code

 

KMP

标签:cstring   namespace   ons   begin   out   hide   mes   题意   math   

原文地址:https://www.cnblogs.com/klaycf/p/9818773.html

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