Блог пользователя weakestOsuPlayer_244

Автор weakestOsuPlayer_244, история, 4 года назад, По-английски

Hello guys.

I was trying the problem https://codeforces.me/contest/182/problem/D

The intended complexity of my solution is supposed to be $$$O(n\sqrt{n})$$$ but somehow I was repeatedly getting TLE. When I switched the concerned part where I was using + for concatenation of two strings with append it got accepted.

I went over to stackoverflow for figuring out the cause but I couldn't understand much of it besides trying the reserve keyword. I also tried using the reserve keyword for reserving space for the string but it resulted in TLE as well.

Here are my submissions:-

https://codeforces.me/contest/182/submission/82678284 -Using append.

https://codeforces.me/contest/182/submission/82677975 -Using + for concatenation.

  • Проголосовать: нравится
  • +1
  • Проголосовать: не нравится

»
4 года назад, # |
Rev. 2   Проголосовать: нравится +3 Проголосовать: не нравится

Using temp1=temp1+temp2 takes O(n) as it copies the first string, adds the second to it and then stores it back in first Edit: Someone please correct me in the comments if I am wrong

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится +3 Проголосовать: не нравится

    It's probably O(n) for a single operation but repeating it over and over seems to tend towards higher complexity. (Otherwise my code would have gotten accepted)

    I think so..

»
4 года назад, # |
  Проголосовать: нравится +7 Проголосовать: не нравится

Basically s=s+t creates a new object by copy s, then appends t, then moving the result to s. s+=t simply appends t, without copying s.

»
4 года назад, # |
  Проголосовать: нравится +4 Проголосовать: не нравится

If there are 'n' strings of length 'x' then time complexity of concatenation will be O(x*n^2). Appending gives a linear time complexity.

»
4 года назад, # |
Rev. 2   Проголосовать: нравится +4 Проголосовать: не нравится

I ran and got AC with your code by replacing a=a+b with a+=b. The runtime difference is strikingly large. The AC submission ran for just 124ms

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится +4 Проголосовать: не нравится

    Yes thanks for your reply. I changed it and it got AC too. Using a+=b; probably prevents creation of the new object as stated above by spookywooky.