Python Optimisation for Round 867 G1. Magic Triples (Easy Version)

Правка en5, от drugkeeper, 2023-05-05 11:17:28

I was doing G1 (https://mirror.codeforces.com/contest/1822/problem/G1) and came up with this solution which is O(n * sqrt(m)) as stated in the editorial. This TLEs in testcase 13 due to constant factors.

TLE Code 1

I went to further optimise my code as shown here, which TLEs in testcase 16:

TLE Code 2

Main changes:

  1. Use faster output
  2. Use Counter instead of array to count, which is faster (this helped the most, and got me past testcase 13). In another solution, I initialised the count array at the very start instead of for each testcase which helped me pass everything.
  3. Got rid of unnecessary variables, if else checks and array / counter access.
  4. Use for loop instead of while loop

However, this still TLEs due to Testcase 16, which is a hash hack for Counter. If I sort the input beforehand, my code passes!

Code that works

Note that Python is too slow to pass all testcases (it fails at testcase 13), but PyPy works.

I have a few questions for the people well versed in python:

  1. Why does sorting the input help get rid of the Counter hash hack testcase TLE?
  2. Is it possible to make Python pass all testcases? (Edit: I found a submission that works in python https://mirror.codeforces.com/contest/1822/submission/203361435)

I hope you can answer my questions, if not, I hope you have learnt something from my blog. Thank you!

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en5 Английский drugkeeper 2023-05-05 11:17:28 40
en4 Английский drugkeeper 2023-05-05 11:16:13 112
en3 Английский drugkeeper 2023-05-05 10:40:41 167
en2 Английский drugkeeper 2023-05-05 10:11:16 325
en1 Английский drugkeeper 2023-05-05 10:08:17 3049 Initial revision (published)