-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathG4G_LCS.cpp
More file actions
452 lines (391 loc) · 12.6 KB
/
G4G_LCS.cpp
File metadata and controls
452 lines (391 loc) · 12.6 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//https://www.geeksforgeeks.org/suffix-tree-application-5-longest-common-substring-2/
// A C program to implement Ukkonen's Suffix Tree Construction
// Here we build generalized suffix tree for two strings
// And then we find longest common substring of the two input strings
#include<bits/stdc++.h>
using std::string;
int max_char = 256;
namespace G4G {
struct SuffixTreeNode {
struct SuffixTreeNode **children;
//pointer to other node via suffix link
struct SuffixTreeNode *suffixLink;
/*(start, end) interval specifies the edge, by which the
node is connected to its parent node. Each edge will
connect two nodes, one parent and one child, and
(start, end) interval of a given edge will be stored
in the child node. Lets say there are two nods A and B
connected by an edge with indices (5, 8) then this
indices (5, 8) will be stored in node B. */
int start;
int *end;
/*for leaf nodes, it stores the index of suffix for
the path from root to leaf*/
int suffixIndex;
};
typedef struct SuffixTreeNode Node;
char text[10000000]; //Input string
int hashtag_loc = 0; // location of #
Node *root = NULL; //Pointer to root node
/*lastNewNode will point to newly created internal node,
waiting for it's suffix link to be set, which might get
a new suffix link (other than root) in next extension of
same phase. lastNewNode will be set to NULL when last
newly created internal node (if there is any) got it's
suffix link reset to new internal node created in next
extension of same phase. */
Node *lastNewNode = NULL;
Node *activeNode = NULL;
/*activeEdge is represented as input string character
index (not the character itself)*/
int activeEdge = -1;
int activeLength = 0;
// remainingSuffixCount tells how many suffixes yet to
// be added in tree
int remainingSuffixCount = 0;
int leafEnd = -1;
int *rootEnd = NULL;
int *splitEnd = NULL;
int size = -1; //Length of input string
int size1 = 0; //Size of 1st string
Node *newNode(int start, int *end) {
Node *node = (Node*) malloc(sizeof(Node));
node->children = (SuffixTreeNode **) malloc(sizeof(SuffixTreeNode*) * max_char);
for (int i = 0; i < max_char; i++) {
node->children[i] = NULL;
}
/*For root node, suffixLink will be set to NULL
For internal nodes, suffixLink will be set to root
by default in current extension and may change in
next extension*/
node->suffixLink = root;
node->start = start;
node->end = end;
/*suffixIndex will be set to -1 by default and
actual suffix index will be set later for leaves
at the end of all phases*/
node->suffixIndex = -1;
return node;
}
int edgeLength(Node *n) {
if (n == root) {
return 0;
}
return *(n->end) - (n->start) + 1;
}
int walkDown(Node *currNode) {
/*activePoint change for walk down (APCFWD) using
Skip/Count Trick (Trick 1). If activeLength is greater
than current edge length, set next internal node as
activeNode and adjust activeEdge and activeLength
accordingly to represent same activePoint*/
if (activeLength >= edgeLength(currNode)) {
activeEdge += edgeLength(currNode);
activeLength -= edgeLength(currNode);
activeNode = currNode;
return 1;
}
return 0;
}
void extendSuffixTree(int pos) {
/*Extension Rule 1, this takes care of extending all
leaves created so far in tree*/
leafEnd = pos;
/*Increment remainingSuffixCount indicating that a
new suffix added to the list of suffixes yet to be
added in tree*/
remainingSuffixCount++;
/*set lastNewNode to NULL while starting a new phase,
indicating there is no internal node waiting for
it's suffix link reset in current phase*/
lastNewNode = NULL;
//Add all suffixes (yet to be added) one by one in tree
while (remainingSuffixCount > 0) {
if (activeLength == 0) {
activeEdge = pos;
}
// There is no outgoing edge starting with
// activeEdge from activeNode
if (activeNode->children[(unsigned char) text[activeEdge]] == NULL) {
activeNode->children[(unsigned char) text[activeEdge]] = newNode(pos, &leafEnd);
/*A new leaf edge is created in above line starting
from an existing node (the current activeNode), and
if there is any internal node waiting for it's suffix
link get reset, point the suffix link from that last
internal node to current activeNode. Then set lastNewNode
to NULL indicating no more node waiting for suffix link
reset.*/
if (lastNewNode != NULL) {
lastNewNode->suffixLink = activeNode;
lastNewNode = NULL;
}
}
// There is an outgoing edge starting with activeEdge
// from activeNode
else {
// Get the next node at the end of edge starting
// with activeEdge
Node *next = activeNode->children[(unsigned char) text[activeEdge]];
if (walkDown(next)) {
//Start from next node (the new activeNode)
continue;
}
/*Extension Rule 3 (current character being processed
is already on the edge)*/
if (text[next->start + activeLength] == text[pos]) {
//If a newly created node waiting for it's
//suffix link to be set, then set suffix link
//of that waiting node to current active node
if (lastNewNode != NULL && activeNode != root) {
lastNewNode->suffixLink = activeNode;
lastNewNode = NULL;
}
activeLength++;
/*STOP all further processing in this phase
and move on to next phase*/
break;
}
/*We will be here when activePoint is in middle of
the edge being traversed and current character
being processed is not on the edge (we fall off
the tree). In this case, we add a new internal node
and a new leaf edge going out of that new node. This
is Extension Rule 2, where a new leaf edge and a new
internal node get created*/
splitEnd = (int*) malloc(sizeof(int));
*splitEnd = next->start + activeLength - 1;
//New internal node
Node *split = newNode(next->start, splitEnd);
activeNode->children[(unsigned char) text[next->start]] = split;
//New leaf coming out of new internal node
split->children[(unsigned char) text[pos]] = newNode(pos, &leafEnd);
next->start += activeLength;
split->children[(unsigned char) text[next->start]] = next;
/*We got a new internal node here. If there is any
internal node created in last extensions of same
phase which is still waiting for it's suffix link
reset, do it now.*/
if (lastNewNode != NULL) {
/*suffixLink of lastNewNode points to current newly
created internal node*/
lastNewNode->suffixLink = split;
}
/*Make the current newly created internal node waiting
for it's suffix link reset (which is pointing to root
at present). If we come across any other internal node
(existing or newly created) in next extension of same
phase, when a new leaf edge gets added (i.e. when
Extension Rule 2 applies is any of the next extension
of same phase) at that point, suffixLink of this node
will point to that internal node.*/
lastNewNode = split;
}
/* One suffix got added in tree, decrement the count of
suffixes yet to be added.*/
remainingSuffixCount--;
if (activeNode == root && activeLength > 0) {
activeLength--;
activeEdge = pos - remainingSuffixCount + 1;
} else if (activeNode != root) {
activeNode = activeNode->suffixLink;
}
}
}
void print(int i, int j)
{
int k;
for (k = i; k <= j && text[k] != '#'; k++)
printf("%c", text[k]);
if (k <= j)
printf("#");
}
//Print the suffix tree as well along with setting suffix index
//So tree will be printed in DFS manner
//Each edge along with it's suffix index will be printed
void setSuffixIndexByDFS(Node *n, int labelHeight)
{
if (n == NULL) return;
if (n->start != -1) //A non-root node
{
//Print the label on edge from parent to current node
//Uncomment below line to print suffix tree
//print(n->start, *(n->end));
}
int leaf = 1;
int i;
for (i = 0; i < max_char; i++)
{
if (n->children[i] != NULL)
{
//Uncomment below two lines to print suffix index
// if (leaf == 1 && n->start != -1)
// printf(" [%d]\n", n->suffixIndex);
//Current node is not a leaf as it has outgoing
//edges from it.
leaf = 0;
setSuffixIndexByDFS(n->children[i], labelHeight +
edgeLength(n->children[i]));
}
}
if (leaf == 1)
{
if (hashtag_loc >= n->start && hashtag_loc <= *(n->end)) {
n->end = (int*) malloc(sizeof(int));
*(n->end) = hashtag_loc;
}
/*for (i = n->start; i <= *(n->end); i++)
{
if (text[i] == '#')
{
n->end = (int*) malloc(sizeof(int));
*(n->end) = i;
}
}*/
n->suffixIndex = size - labelHeight;
//Uncomment below line to print suffix index
// printf(" [%d]\n", n->suffixIndex);
}
}
void freeSuffixTreeByPostOrder(Node *n)
{
if (n == NULL)
return;
int i;
for (i = 0; i < max_char; i++)
{
if (n->children[i] != NULL)
{
freeSuffixTreeByPostOrder(n->children[i]);
}
}
if (n->suffixIndex == -1)
free(n->end);
free(n);
}
/*Build the suffix tree and print the edge labels along with
suffixIndex. suffixIndex for leaf edges will be >= 0 and
for non-leaf edges will be -1*/
void buildSuffixTree()
{
size = strlen(text);
int i;
rootEnd = (int*) malloc(sizeof(int));
*rootEnd = - 1;
/*Root is a special node with start and end indices as -1,
as it has no parent from where an edge comes to root*/
root = newNode(-1, rootEnd);
activeNode = root; //First activeNode will be root
for (i = 0; i < size; i++)
extendSuffixTree(i);
int labelHeight = 0;
setSuffixIndexByDFS(root, labelHeight);
}
int doTraversal(Node *n, int labelHeight, int* maxHeight,
int* substringStartIndex)
{
if (n == NULL)
{
return 0;
}
int i = 0;
int ret = -1;
if (n->suffixIndex < 0) //If it is internal node
{
for (i = 0; i < max_char; i++)
{
if (n->children[i] != NULL)
{
ret = doTraversal(n->children[i], labelHeight +
edgeLength(n->children[i]),
maxHeight, substringStartIndex);
if (n->suffixIndex == -1)
n->suffixIndex = ret;
else if ((n->suffixIndex == -2 && ret == -3) ||
(n->suffixIndex == -3 && ret == -2) ||
n->suffixIndex == -4)
{
n->suffixIndex = -4;//Mark node as XY
//Keep track of deepest node
if (*maxHeight < labelHeight)
{
*maxHeight = labelHeight;
*substringStartIndex = *(n->end) -
labelHeight + 1;
}
}
}
}
}
else if (n->suffixIndex > -1 && n->suffixIndex < size1) //suffix of X
return -2;//Mark node as X
else if (n->suffixIndex >= size1) //suffix of Y
return -3;//Mark node as Y
return n->suffixIndex;
}
string getLongestCommonSubstring()
{
int maxHeight = 0;
int substringStartIndex = 0;
doTraversal(root, 0, &maxHeight, &substringStartIndex);
string ans = "";
int k;
for (k = 0; k < maxHeight; k++)
ans += text[k + substringStartIndex];
return ans;
}
string LCS(string a, string b, char maxchar) {
max_char = maxchar + 3;
size1 = a.size();
string combined = a + (char)(maxchar+1) + b + (char)(maxchar+2);
strcpy(text, combined.c_str());
hashtag_loc = a.size();
buildSuffixTree();
string ans = getLongestCommonSubstring();
freeSuffixTreeByPostOrder(root);
return ans;
}
// driver program to test above functions
int main(int argc, char *argv[])
{
size1 = 7;
printf("Longest Common Substring in xabxac and abcabxabcd is: ");
strcpy(text, "xabxac#abcabxabcd$"); buildSuffixTree();
printf("%s\n", getLongestCommonSubstring().c_str());
//Free the dynamically allocated memory
freeSuffixTreeByPostOrder(root);
size1 = 10;
printf("Longest Common Substring in xabxaabxa and babxba is: ");
strcpy(text, "xabxaabxa#babxba$"); buildSuffixTree();
printf("%s\n", getLongestCommonSubstring().c_str());
//Free the dynamically allocated memory
freeSuffixTreeByPostOrder(root);
size1 = 14;
printf("Longest Common Substring in GeeksforGeeks and GeeksQuiz is: ");
strcpy(text, "GeeksforGeeks#GeeksQuiz$"); buildSuffixTree();
printf("%s\n", getLongestCommonSubstring().c_str());
//Free the dynamically allocated memory
freeSuffixTreeByPostOrder(root);
size1 = 26;
printf("Longest Common Substring in OldSite:GeeksforGeeks.org");
printf(" and NewSite:GeeksQuiz.com is: ");
strcpy(text, "OldSite:GeeksforGeeks.org#NewSite:GeeksQuiz.com$");
buildSuffixTree();
printf("%s\n", getLongestCommonSubstring().c_str());
//Free the dynamically allocated memory
freeSuffixTreeByPostOrder(root);
size1 = 6;
printf("Longest Common Substring in abcde and fghie is: ");
strcpy(text, "abcde#fghie$"); buildSuffixTree();
printf("%s\n", getLongestCommonSubstring().c_str());
//Free the dynamically allocated memory
freeSuffixTreeByPostOrder(root);
size1 = 6;
printf("Longest Common Substring in pqrst and uvwxyz is: ");
strcpy(text, "pqrst#uvwxyz$"); buildSuffixTree();
printf("%s\n", getLongestCommonSubstring().c_str());
//Free the dynamically allocated memory
freeSuffixTreeByPostOrder(root);
return 0;
}
}
//This code is contributed by NarasingaNikhil and Yadav3ankit