Can anyone pls tell which is the best way to avoid tle in cpp…i am tired of searching tags…thanks
Use a better algorithm.
@chaseme… Main reason of coming TLE is that your algorithm is not efficient .It does not depend on any programming language.If you want to avoid TLE then apply an algorithm with lesser time complexity
Algorithm ( This is the first thing you have to take care about )
Apart from that
- Use scanf and printf instead of cin and cout , the latter is 3 times slower than the scanf nd printf
- Try to precalculate most of the things that remains constant through out the code
You can follow the method that infinitum stated. But if you insist on using cin/cout. Add this line just after your main
ios_base::sync_with_stdio(0); What this does is it terminates the synch between the standard IO streams. You can read more about it here.
The first and foremost thing is to get a good algorithm. If your algorithm is correct you have 90% of your work done. How you get to it depends on you.Now once you have an algorithm here are some simple tips regarding implementation that will help speed up your code:
I/O Methods: The easiest optimization is changing your input/output method. Using fast input methods like use of getchar_unlocked() can speed up your program by 10-20 times in programs with very large input/output limits. You can read more about fast I/O here
Iterate : Recursion normally involves a large number of function calls. At each step the system may have to push and pop a large amount of data from the system stack which has a lot of overhead. Try to use iterative solutions wherever possible.However they are normally more difficult to think of than recursive solutions.
3)MACROS: Using functions again involves the pushing and popping of large data on the system stack as execution will have to jump from one segment of memory to another. However when you use macros, the macro call is directly replaced by the full code defined for macro. Hence the execution continues in the same block of memory and there is no need of a jump or system stack. This reduces the overhead and helps speed up your code.
my algorithm is maximum optimised…i only need to know how to read input and output fast…