算法总结:Manacher

先贴上大佬的Manacher讲解,用的Python,讲的很清楚:https://segmentfault.com/a/1190000003914228

然后讲一下自己对一些关键部分的理解(基于我的c++ code)和大佬的讲解:

第十九行代码:如果与i对应的已经计算出的j很小的化,那么这时候i的RL[i] = RL[j] = RL[2*pos - 1]

其他的大佬已经讲的很清楚了,很好理解,贴下自己的c++代码:

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <algorithm>
 5 #include <string>
 6 #define MAXN 1000001
 7 using namespace std;
 8 
 9 string s = "sator arepo tenet opera rotas";
10 
11 int Manacher(string res)
12 {
13     int i, pos = 0, MaxRight = 0, MaxLen = 0;
14     int Len = res.size();
15     int RL[Len];
16     memset(RL, 0, sizeof(RL));
17     for (i = 0; i < Len; ++i)
18     {
19         if (i < MaxRight)
20             RL[i] = min(RL[2*pos-i], MaxRight - i);
21         else
22             RL[i] = 1;
23 
24         while (i + RL[i] < Len && i - RL[i] >= 0 && res[i - RL[i]] == res[i + RL[i]])
25             RL[i]++;
26         if (i + RL[i] - 1 > MaxRight)
27         {
28             MaxRight = i + RL[i] - 1;
29             pos = i;
30         }
31         MaxLen = max(MaxLen, RL[i]);
32     }
33 
34     return MaxLen - 1;
35 }
36 
37 int main()
38 {
39     string res;
40     res += '#';
41     for (unsigned int i = 0; i < s.size(); ++i)
42     {
43         res += s[i];
44         res += '#';
45     }
46 
47     cout << Manacher(res) << endl;
48 
49     return 0;
50 }

猜你喜欢

转载自www.cnblogs.com/ducklu/p/9120128.html
今日推荐