fork(1) download
  1. // A C program to implement Ukkonen's Suffix Tree Construction
  2. // And and then create suffix array in linear time
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include <cstddef>
  7. #include <string>
  8. #include <iostream>
  9. #include <time.h>
  10.  
  11. #define MAX_CHAR 256
  12. #define mod 1000000007
  13. #define MAX 100000
  14.  
  15.  
  16. using namespace std;
  17.  
  18. struct SuffixTreeNode {
  19. struct SuffixTreeNode *children[MAX_CHAR];
  20.  
  21. //pointer to other node via suffix link
  22. struct SuffixTreeNode *suffixLink;
  23.  
  24. /*(start, end) interval specifies the edge, by which the
  25.   node is connected to its parent node. Each edge will
  26.   connect two nodes, one parent and one child, and
  27.   (start, end) interval of a given edge will be stored
  28.   in the child node. Lets say there are two nods A and B
  29.   connected by an edge with indices (5, 8) then this
  30.   indices (5, 8) will be stored in node B. */
  31. int start;
  32. int *end;
  33.  
  34. /*for leaf nodes, it stores the index of suffix for
  35.   the path from root to leaf*/
  36. int suffixIndex;
  37. };
  38.  
  39. typedef struct SuffixTreeNode Node;
  40.  
  41. string text;
  42. //char text[MAX]; //Input string
  43. Node *root = NULL; //Pointer to root node
  44.  
  45. /*lastNewNode will point to newly created internal node,
  46.   waiting for it's suffix link to be set, which might get
  47.   a new suffix link (other than root) in next extension of
  48.   same phase. lastNewNode will be set to NULL when last
  49.   newly created internal node (if there is any) got it's
  50.   suffix link reset to new internal node created in next
  51.   extension of same phase. */
  52. Node *lastNewNode = NULL;
  53. Node *activeNode = NULL;
  54.  
  55. /*activeEdge is represeted as input string character
  56.   index (not the character itself)*/
  57. int activeEdge = -1;
  58. int activeLength = 0;
  59.  
  60. // remainingSuffixCount tells how many suffixes yet to
  61. // be added in tree
  62. int remainingSuffixCount = 0;
  63. int leafEnd = -1;
  64. int *rootEnd = NULL;
  65. int *splitEnd = NULL;
  66. int size = -1; //Length of input string
  67.  
  68. Node *newNode(int start, int *end)
  69. {
  70. Node *node =(Node*) malloc(sizeof(Node));
  71. int i;
  72. for (i = 0; i < MAX_CHAR; i++)
  73. node->children[i] = NULL;
  74.  
  75. /*For root node, suffixLink will be set to NULL
  76.   For internal nodes, suffixLink will be set to root
  77.   by default in current extension and may change in
  78.   next extension*/
  79. node->suffixLink = root;
  80. node->start = start;
  81. node->end = end;
  82.  
  83. /*suffixIndex will be set to -1 by default and
  84.   actual suffix index will be set later for leaves
  85.   at the end of all phases*/
  86. node->suffixIndex = -1;
  87. return node;
  88. }
  89.  
  90. int edgeLength(Node *n) {
  91. if(n == root)
  92. return 0;
  93. return *(n->end) - (n->start) + 1;
  94. }
  95.  
  96. int walkDown(Node *currNode)
  97. {
  98. /*activePoint change for walk down (APCFWD) using
  99.   Skip/Count Trick (Trick 1). If activeLength is greater
  100.   than current edge length, set next internal node as
  101.   activeNode and adjust activeEdge and activeLength
  102.   accordingly to represent same activePoint*/
  103. if (activeLength >= edgeLength(currNode))
  104. {
  105. activeEdge += edgeLength(currNode);
  106. activeLength -= edgeLength(currNode);
  107. activeNode = currNode;
  108. return 1;
  109. }
  110. return 0;
  111. }
  112.  
  113. void extendSuffixTree(int pos)
  114. {
  115. /*Extension Rule 1, this takes care of extending all
  116.   leaves created so far in tree*/
  117. leafEnd = pos;
  118.  
  119. /*Increment remainingSuffixCount indicating that a
  120.   new suffix added to the list of suffixes yet to be
  121.   added in tree*/
  122. remainingSuffixCount++;
  123.  
  124. /*set lastNewNode to NULL while starting a new phase,
  125.   indicating there is no internal node waiting for
  126.   it's suffix link reset in current phase*/
  127. lastNewNode = NULL;
  128.  
  129. //Add all suffixes (yet to be added) one by one in tree
  130. while(remainingSuffixCount > 0) {
  131.  
  132. if (activeLength == 0)
  133. activeEdge = pos; //APCFALZ
  134.  
  135. // There is no outgoing edge starting with
  136. // activeEdge from activeNode
  137. if (activeNode->children[text[activeEdge]] == NULL)
  138. {
  139. //Extension Rule 2 (A new leaf edge gets created)
  140. activeNode->children[text[activeEdge]] =
  141. newNode(pos, &leafEnd);
  142.  
  143. /*A new leaf edge is created in above line starting
  144.   from an existng node (the current activeNode), and
  145.   if there is any internal node waiting for it's suffix
  146.   link get reset, point the suffix link from that last
  147.   internal node to current activeNode. Then set lastNewNode
  148.   to NULL indicating no more node waiting for suffix link
  149.   reset.*/
  150. if (lastNewNode != NULL)
  151. {
  152. lastNewNode->suffixLink = activeNode;
  153. lastNewNode = NULL;
  154. }
  155. }
  156. // There is an outgoing edge starting with activeEdge
  157. // from activeNode
  158. else
  159. {
  160. // Get the next node at the end of edge starting
  161. // with activeEdge
  162. Node *next = activeNode->children[text[activeEdge]];
  163. if (walkDown(next))//Do walkdown
  164. {
  165. //Start from next node (the new activeNode)
  166. continue;
  167. }
  168. /*Extension Rule 3 (current character being processed
  169.   is already on the edge)*/
  170. if (text[next->start + activeLength] == text[pos])
  171. {
  172. //If a newly created node waiting for it's
  173. //suffix link to be set, then set suffix link
  174. //of that waiting node to curent active node
  175. if(lastNewNode != NULL && activeNode != root)
  176. {
  177. lastNewNode->suffixLink = activeNode;
  178. lastNewNode = NULL;
  179. }
  180.  
  181. //APCFER3
  182. activeLength++;
  183. /*STOP all further processing in this phase
  184.   and move on to next phase*/
  185. break;
  186. }
  187.  
  188. /*We will be here when activePoint is in middle of
  189.   the edge being traversed and current character
  190.   being processed is not on the edge (we fall off
  191.   the tree). In this case, we add a new internal node
  192.   and a new leaf edge going out of that new node. This
  193.   is Extension Rule 2, where a new leaf edge and a new
  194.   internal node get created*/
  195. splitEnd = (int*) malloc(sizeof(int));
  196. *splitEnd = next->start + activeLength - 1;
  197.  
  198. //New internal node
  199. Node *split = newNode(next->start, splitEnd);
  200. activeNode->children[text[activeEdge]] = split;
  201.  
  202. //New leaf coming out of new internal node
  203. split->children[text[pos]] = newNode(pos, &leafEnd);
  204. next->start += activeLength;
  205. split->children[text[next->start]] = next;
  206.  
  207. /*We got a new internal node here. If there is any
  208.   internal node created in last extensions of same
  209.   phase which is still waiting for it's suffix link
  210.   reset, do it now.*/
  211. if (lastNewNode != NULL)
  212. {
  213. /*suffixLink of lastNewNode points to current newly
  214.   created internal node*/
  215. lastNewNode->suffixLink = split;
  216. }
  217.  
  218. /*Make the current newly created internal node waiting
  219.   for it's suffix link reset (which is pointing to root
  220.   at present). If we come across any other internal node
  221.   (existing or newly created) in next extension of same
  222.   phase, when a new leaf edge gets added (i.e. when
  223.   Extension Rule 2 applies is any of the next extension
  224.   of same phase) at that point, suffixLink of this node
  225.   will point to that internal node.*/
  226. lastNewNode = split;
  227. }
  228.  
  229. /* One suffix got added in tree, decrement the count of
  230.   suffixes yet to be added.*/
  231. remainingSuffixCount--;
  232. if (activeNode == root && activeLength > 0) //APCFER2C1
  233. {
  234. activeLength--;
  235. activeEdge = pos - remainingSuffixCount + 1;
  236. }
  237. else if (activeNode != root) //APCFER2C2
  238. {
  239. activeNode = activeNode->suffixLink;
  240. }
  241. }
  242. }
  243.  
  244. void print(int i, int j)
  245. {
  246. int k;
  247. for (k=i; k<=j; k++)
  248. printf("%c", text[k]);
  249. }
  250.  
  251. //Print the suffix tree as well along with setting suffix index
  252. //So tree will be printed in DFS manner
  253. //Each edge along with it's suffix index will be printed
  254. void setSuffixIndexByDFS(Node *n, int labelHeight)
  255. {
  256. if (n == NULL) return;
  257.  
  258. if (n->start != -1) //A non-root node
  259. {
  260. //Print the label on edge from parent to current node
  261. //Uncomment below line to print suffix tree
  262. // print(n->start, *(n->end));
  263. }
  264. int leaf = 1;
  265. int i;
  266. for (i = 0; i < MAX_CHAR; i++)
  267. {
  268. if (n->children[i] != NULL)
  269. {
  270. //Uncomment below two lines to print suffix index
  271. // if (leaf == 1 && n->start != -1)
  272. // printf(" [%d]\n", n->suffixIndex);
  273.  
  274. //Current node is not a leaf as it has outgoing
  275. //edges from it.
  276. leaf = 0;
  277. setSuffixIndexByDFS(n->children[i], labelHeight +
  278. edgeLength(n->children[i]));
  279. }
  280. }
  281. if (leaf == 1)
  282. {
  283. n->suffixIndex = size - labelHeight;
  284. //Uncomment below line to print suffix index
  285. //printf(" [%d]\n", n->suffixIndex);
  286. }
  287. }
  288.  
  289. void freeSuffixTreeByPostOrder(Node *n)
  290. {
  291. if (n == NULL)
  292. return;
  293. int i;
  294. for (i = 0; i < MAX_CHAR; i++)
  295. {
  296. if (n->children[i] != NULL)
  297. {
  298. freeSuffixTreeByPostOrder(n->children[i]);
  299. }
  300. }
  301. if (n->suffixIndex == -1)
  302. free(n->end);
  303. free(n);
  304. }
  305.  
  306. /*Build the suffix tree and print the edge labels along with
  307. suffixIndex. suffixIndex for leaf edges will be >= 0 and
  308. for non-leaf edges will be -1*/
  309. void buildSuffixTree()
  310. {
  311. size = text.length();
  312. //size = strlen(text);
  313.  
  314. int i;
  315. rootEnd = (int*) malloc(sizeof(int));
  316. *rootEnd = - 1;
  317.  
  318. /*Root is a special node with start and end indices as -1,
  319.   as it has no parent from where an edge comes to root*/
  320. root = newNode(-1, rootEnd);
  321.  
  322. activeNode = root; //First activeNode will be root
  323. for (i=0; i<size; i++)
  324. extendSuffixTree(i);
  325. int labelHeight = 0;
  326. setSuffixIndexByDFS(root, labelHeight);
  327. }
  328.  
  329. void doTraversal(Node *n, int suffixArray[], int *idx)
  330. {
  331. if(n == NULL)
  332. {
  333. return;
  334. }
  335. int i=0;
  336. if(n->suffixIndex == -1) //If it is internal node
  337. {
  338. for (i = 0; i < MAX_CHAR; i++)
  339. {
  340. if(n->children[i] != NULL)
  341. {
  342. doTraversal(n->children[i], suffixArray, idx);
  343. }
  344. }
  345. }
  346. //If it is Leaf node other than "$" label
  347. else if(n->suffixIndex > -1 && n->suffixIndex < size)
  348. {
  349. suffixArray[(*idx)++] = n->suffixIndex;
  350. }
  351. }
  352.  
  353. void buildSuffixArray(int suffixArray[])
  354. {
  355. int i = 0;
  356. for(i=0; i< size; i++)
  357. suffixArray[i] = -1;
  358. int idx = 0;
  359. doTraversal(root, suffixArray, &idx);
  360. /* printf("Suffix Array for String ");
  361.   for(i=0; i<size; i++)
  362.   printf("%c", text[i]);
  363.   printf(" is: ");
  364.   for(i=0; i<size; i++)
  365.   printf("%d ", suffixArray[i]);
  366.   printf("\n");*/
  367. }
  368.  
  369. bool isSuffix (string &str, int iStart, int iEnd, int jStart)
  370. {
  371. for (int i = iStart, j = jStart; i <= iEnd; i++, j++)
  372. if (str[i] != str[j])
  373. return false;
  374. return true;
  375. }
  376.  
  377. void isPalin(string &str, int i, int j, int &count)
  378. {
  379. int start = i;
  380. int end = j;
  381.  
  382. while (i < end)
  383. {
  384. if (str[i] == str[j])
  385. {
  386. if (isSuffix(str, start, i, j))
  387. {
  388. count++;
  389. count %= mod;
  390.  
  391. }
  392. i++, j--;
  393. }
  394. else
  395. {
  396. break;
  397. }
  398. }
  399.  
  400. }
  401.  
  402.  
  403. // driver program to test above functions
  404. int main(int argc, char *argv[])
  405. {
  406. int t;
  407. //cin >> t;
  408. t = 1;
  409.  
  410. while (t > 0) {
  411.  
  412. cin >> text;
  413.  
  414. text += "$";
  415.  
  416. int start_s = clock();
  417.  
  418. //buildSuffixArray(str, str.length());
  419. buildSuffixTree();
  420. size--;
  421. int *suffixArray =(int*) malloc(sizeof(int) * size);
  422. buildSuffixArray(suffixArray);
  423. text.pop_back();
  424. int n = text.length();
  425.  
  426. int count = 0;
  427.  
  428. for(int i = 0;i < n;i++) {
  429.  
  430. int begin_suffix = suffixArray[i];
  431. int end_suffix = n - suffixArray[i];
  432.  
  433. for (int j = 1; j <= end_suffix; j++) {
  434.  
  435. if (j >= 2) {
  436. int left = begin_suffix;
  437. int right = begin_suffix + j - 1;
  438.  
  439. isPalin(text, left, right, count);
  440. }
  441. }
  442. }
  443.  
  444. //Free the dynamically allocated memory
  445. freeSuffixTreeByPostOrder(root);
  446. free(suffixArray);
  447.  
  448.  
  449. cout << count << endl;
  450.  
  451. int stop_s = clock();
  452. float run_time = (stop_s - start_s) / double(CLOCKS_PER_SEC);
  453. //cout << endl << "palindromic borders \t\tExecution time = " << run_time << " seconds" << endl;
  454.  
  455. t--;
  456. }
  457.  
  458. return 0;
  459. }
  460.  
Success #stdin #stdout 0s 3476KB
stdin
ababa
stdout
5