Advertisement
a53

subsecventa

a53
Dec 8th, 2019
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. /// A C program to implement Manacher’s Algorithm
  2. #include <fstream>
  3. #include <cstdio>
  4. #include <cstring>
  5. using namespace std;
  6. ofstream g("subsecventa.out");
  7. char text[100001];
  8.  
  9. void findLongestPalindromicString()
  10. {
  11. int N=strlen(text);
  12. if(N==0)
  13. return;
  14. N=2*N+1; ///Position count
  15. int L[N]; ///LPS Length Array
  16. L[0]=0;
  17. L[1]=1;
  18. int C=1; ///centerPosition
  19. int R=2; ///centerRightPosition
  20. int i=0; ///currentRightPosition
  21. int iMirror; ///currentLeftPosition
  22. int maxLPSLength=0;
  23. int maxLPSCenterPosition=0;
  24. int start=-1;
  25. int end=-1;
  26. int diff=-1;
  27. ///Uncomment it to print LPS Length array
  28. ///printf("%d %d ", L[0], L[1]);
  29. for(i=2;i<N;++i)
  30. { ///get currentLeftPosition iMirror for currentRightPosition i
  31. iMirror =2*C-i;
  32. L[i]=0;
  33. diff=R-i;
  34. if(diff>0) ///If currentRightPosition i is within centerRightPosition R
  35. L[i]=min(L[iMirror],diff);
  36. ///Attempt to expand palindrome centered at currentRightPosition i
  37. ///Here for odd positions, we compare characters and
  38. ///if match then increment LPS Length by ONE
  39. ///If even position, we just increment LPS by ONE without
  40. ///any character comparison
  41. while(((i+L[i])<N&&(i-L[i])>0)&&
  42. (((i+L[i]+1)%2==0)||
  43. (text[(i+L[i]+1)/2]==text[(i-L[i]-1)/2])))
  44. {
  45. L[i]++;
  46. }
  47.  
  48. if(L[i]>maxLPSLength) /// Track maxLPSLength
  49. {
  50. maxLPSLength=L[i];
  51. maxLPSCenterPosition=i;
  52. }
  53. ///If palindrome centered at currentRightPosition i
  54. ///expand beyond centerRightPosition R,
  55. ///adjust centerPosition C based on expanded palindrome.
  56. if(i+L[i]>R)
  57. {
  58. C=i;
  59. R=i+L[i];
  60. }
  61. }
  62. if(maxLPSLength>1)
  63. {
  64. start=(maxLPSCenterPosition-maxLPSLength)/2;
  65. end=start+maxLPSLength-1;
  66. g<<maxLPSLength<<'\n';
  67. for(i=start;i<=end;i++)
  68. g<<text[i];
  69. }
  70. else
  71. g<<1<<'\n'<<text[0];
  72. }
  73.  
  74. int main()
  75. {
  76. ifstream f("subsecventa.in");
  77. f>>text;
  78. findLongestPalindromicString();
  79. return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement