time limit exceeded on O(n) Z-func in problem below
Difference between ru2 and ru3, changed 4 character(s)
Hello!↵

I have TLE on 23 test with O(n) (I think so) Z-function. I want to reverse origin string and just use Z-func. Where is the problem?↵
~~~~~↵
#include <iostream>↵
#include <vector>↵
#include <string>↵
#include <algorithm>↵

using namespace std;↵

void z_function (string s) {↵
    int n = (int) s.length();↵
    string str = s;↵
    //reverse(str.begin(), str.end());↵
    for (int i = 0; i < str.length() / 2; i++) {↵
        swap(str[i], str[str.length() &mdash; 1 &mdash; i]);↵
    }↵
    s += '#';↵
    s += str;↵
    n = s.length();↵
    //cout << s << '\n';↵
    vector<int> z (n);↵
    for (int i=str.length() + 1, l=0, r=0; i<n; ++i) {↵
        if (i <= r)↵
            z[i] = min (r-i+1, z[i-l]);↵
        while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {↵
            //cout << "z[i] = " << z[i] << ' ' << s[i] << ' ' << "i + z[i] = " << i +z[i] << ' ' << s[i +z[i]] << '\n';↵
            ++z[i];↵
        }↵
        if (i+z[i]-1 > r)↵
            l = i,  r = i+z[i]-1;↵
        //cout << z[i] << ' ';↵
    }↵

    int ans = 1;↵
    for (int i = str.length() + 1; i < z.size(); i++) ans = max(ans, z[i]);↵
    cout << ans;↵
}↵

int main() {↵
    ios_base::sync_with_stdio(0);↵
    cin.tie(0);↵
    cout.tie(0);↵
    ↵
    string s;↵
    cin >> s;↵
    int n = s.length();↵

    z_function(s);↵

}


~~~~~↵

[problem:https://codeforces.com/edu/course/2/lesson/3/4/practice/contest/272262/problem/D]

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
ru5 Russian SirodgevAlexander_ 2024-02-11 12:54:12 1163
ru4 Russian SirodgevAlexander_ 2024-02-11 12:53:16 18
ru3 Russian SirodgevAlexander_ 2024-02-11 12:52:39 4 Мелкая правка: 'n(s);\n\n}~~~~~\n\n[' -> 'n(s);\n\n}\n\n~~~~~\n\n['
ru2 Russian SirodgevAlexander_ 2024-02-11 12:52:13 1177
ru1 Russian SirodgevAlexander_ 2024-02-11 12:49:35 314 Первая редакция (опубликовано)