-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpalindromicTree.cpp
More file actions
116 lines (107 loc) · 2.5 KB
/
Copy pathpalindromicTree.cpp
File metadata and controls
116 lines (107 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/**************************************************************************************
Palindrome tree. Useful structure to deal with palindromes in strings. O(N)
This code counts number of palindrome substrings of the string.
Based on problem 1750 from informatics.mccme.ru:
http://informatics.mccme.ru/moodle/mod/statements/view.php?chapterid=1750
https://www.spoj.com/problems/NUMOFPAL
**************************************************************************************/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mem(a,x) memset(a,x,sizeof(a))
const int MX=200000;
struct Node
{
int len;
int link;
int num; // cnt of differennt palindrome
int occur; // cnt of same palindromes
int nxt[26];
};
Node T[MX];
int len; // string length
string s;
int node; // node 1 - root with len -1, node 2 - root with len 0
int suff; // max suffix palindrome
int New()
{
node++;
T[node].len=T[node].link=0;
T[node].num=T[node].occur=0;
mem(T[node].nxt,0);
return node;
}
bool add(int pos)
{
int cur=suff, curlen=0;
int let=s[pos]-'a';
while(true) //Finding maximum length palindromic suffix
{
curlen=T[cur].len;
if(pos-1-curlen>=0 && s[pos-1-curlen]==s[pos]) break;
cur=T[cur].link;
}
if(T[cur].nxt[let]) //Existing node
{
suff=T[cur].nxt[let];
return false;
}
suff = New();
T[node].len=T[cur].len+2;
T[cur].nxt[let]=node;
if(T[node].len==1) //Single character, connected with root
{
T[node].link=2;
T[node].num=1;
return true;
}
while(true) //Finding suffix link
{
cur=T[cur].link;
curlen=T[cur].len;
if(pos-1-curlen>=0 && s[pos-1-curlen]==s[pos])
{
T[node].link=T[cur].nxt[let];
break;
}
}
T[node].num=1+T[T[node].link].num;
return true;
}
void initTree()
{
node=suff=2;
T[1].len=-1, T[2].len=0;
T[1].link=1, T[2].link=1;
mem(T[1].nxt,0);
mem(T[2].nxt,0);
}
ll totalpalindrome=0;
void buildTree()
{
initTree();
for(int i=0;i<len;i++)
{
add(i); T[suff].occur++;
totalpalindrome+=T[suff].num;
}
}
ll countPalindromes()
{
ll cnt=0;
for(int i=node;i>2;i--)
{
T[T[i].link].occur+=T[i].occur;
cnt+=T[i].occur;
}
return cnt;
}
int main()
{
cin>>s;
len=s.size();
buildTree();
cout<<totalpalindrome<<endl;
//cout<<countPalindromes()<<endl;
return 0;
}