ENG  RUSTimus Online Judge
Online Judge
Problems
Authors
Online contests
About Online Judge
Frequently asked questions
Site news
Webboard
Links
Problem set
Submit solution
Judge status
Guide
Register
Update your info
Authors ranklist
Current contest
Scheduled contests
Past contests
Rules
back to board

Discussion of Problem 1423. String Tale

Solution using Z-function is O(n) but gives TLA
Posted by Anton 13 Apr 2023 23:25
Unexpected result: the solution using z-function is O(n) but gives TLA on the 8th test. The solution doesn't pass so I will leave the code with it here. I'm wondering if it really doesn't pass the 8th test because it is too slow though is O(n), or if there's just some kind of error in my algorithm.

vi ZFunction(string &p, string &s) {
  int n = (int) p.size();
  vector<int> z(n + 1);
  for (int i = 0, l = 0, r = 0; i < n; ++i) {
    if (i <= r)
      z[i] = min(r - i + 1, z[i - l]);
    while (i + z[i] < n && p[z[i]] == s[i + z[i]])
      ++z[i];
    if (i + z[i] - 1 > r)
      l = i, r = i + z[i] - 1;
  }
  return z;
}

  ....
  vector<int> z_func = ZFunction(s1, s2);
  vector<int> z_func2 = ZFunction(s2, s1);
  for (int i = 0; i < n; ++i) {
    if (z_func[i] == n - i && z_func2[n - i] == i) {
      cout << i;
      return;
    }
  }
  cout << "-1";

Edited by author 13.04.2023 23:25

Edited by author 13.04.2023 23:25

Edited by author 13.04.2023 23:27