Advertisement
dipBRUR

18

Nov 19th, 2017
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. // Algorithm : Palindromic Tree
  2. // Complexity : O(n)
  3.  
  4. struct node {
  5. int next[26];
  6. int len;
  7. int sufflink;
  8. } tree[mx];
  9.  
  10. int max_len, len;
  11. string s;
  12. int num, suff;
  13.  
  14. void addLetter(int pos) {
  15. int cur = suff;
  16. int curlen;
  17. int let = s[pos] - 'a';
  18. while (true) {
  19. curlen = tree[cur].len;
  20. int id = pos - 1 - curlen;
  21. if (id >= 0 && s[id] == s[pos])
  22. break;
  23. cur = tree[cur].sufflink;
  24. }
  25. if (tree[cur].next[let]) {
  26. suff = tree[cur].next[let];
  27. return;
  28. }
  29. num++; // create new node number
  30. suff = num;
  31. tree[num].len = tree[cur].len + 2; // new node
  32. tree[cur].next[let] = num;
  33. max_len = max(tree[num].len, max_len);
  34. if (tree[num].len == 1) {
  35. tree[num].sufflink = 2;
  36. return;
  37. }
  38. while (true) {
  39. cur = tree[cur].sufflink;
  40. curlen = tree[cur].len;
  41. int id = pos - 1 - curlen;
  42. if (id >= 0 && s[id] == s[pos]) {
  43. tree[num].sufflink = tree[cur].next[let];
  44. break;
  45. }
  46. }
  47. return;
  48. }
  49.  
  50. void init_palindrome_tree() {
  51. num = 2; suff = 2;
  52. tree[1].len = -1; tree[1].sufflink = 1;
  53. tree[2].len = 0; tree[2].sufflink = 1;
  54. }
  55.  
  56. Application:
  57. 1. Find maximum length palindromic substring :
  58. Ans : return max_len
  59. 2. Find all distinct palindromic substring :
  60. Ans : total number of nodes - 2. Set start index & finish
  61. index in the structure to print the string.
  62. 3. How many new palindrome are added?
  63. Ans : Distinct : add letter & print node num.
  64. Not Distinct : node num + sufflink.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement