fork download
  1. #include <algorithm>
  2. #include <string>
  3. #include <vector>
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. string theString; //HACK
  9. int n;
  10. vector<vector<int> > _memo;
  11.  
  12. int f(int i, int j); // Need forward declaration for mutual recursion
  13.  
  14. int m(int i, int j) {
  15. return static_cast<int>(theString[i - 1] == theString[j - 1] && i < j) + f(i - 1, j - 1);
  16. }
  17.  
  18. int f(int i, int j) {
  19. if (i == 0 || j == 0) {
  20. return 0;
  21. }
  22.  
  23. // Make sure the DP table is big enough
  24. if (_memo.size() <= i) {
  25. _memo.resize(i + 1);
  26. }
  27. if (_memo[i].size() <= j) {
  28. _memo[i].resize(j + 1, -1); // -1 means "dunno yet"
  29. }
  30.  
  31. if (_memo[i][j] == -1) {
  32. // Dunno the answer yet, need to compute it
  33. _memo[i][j] = max(max(f(i - 1, j), f(i, j - 1)), m(i, j));
  34. }
  35.  
  36. return _memo[i][j];
  37. }
  38.  
  39. int longestSACS(string s) {
  40. // Clear the DP table
  41. _memo.clear();
  42. theString = s;
  43. n = theString.size();
  44.  
  45. int x = 0;
  46. for (int i = 0; i <= n; ++i) {
  47. x = max(x, f(i, n));
  48. }
  49.  
  50. return x;
  51. }
  52.  
  53. int main(int argc, char **argv) {
  54. cout << longestSACS("1213213515") << '\n';
  55. cout << longestSACS("1213243545") << '\n';
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
6
5