Check out these two submissions for the same question.
These two submissions are almost identical yet there is a huge difference in time taken. That’s because I have used endl in solution 1 and “\n” in solution 2 to print newline.
When we have to print large output as in this problem, it is better to use “\n” instead of endl. Just wanted to point this out for newbie’s.
In last months Long Challenge, the problem ENGXOR also had the same problem. It also gave a TLE to the users who were using an
endl instead of
Well Input/output operations take much more time than other operation we include in our code.
‘endl’ is not just about adding a newline…it also flushes the buffer, which is a very expensive task and it consumes time. While “\n” just means adding a newline.
That’s is why a solution with endl takes more time than a solution with “\n” due to flushing the buffer repeatedly every time it appears. Generally, i will suggest not to use ‘endl’ because as soon as buffer gets full it is flushed automatically. if in some cases you need to flush the output insert ‘std::flush’ into the stream.