Many people use endl
and '\n'
interchangeably without understanding the key difference between the functioning of the two.
Sometimes using endl
in place of '\n'
can end up getting you a TLE which otherwise would have been an AC with the use of '\n'
.
So let's see what the difference is.
'\n'
: It inserts a new line to the output stream.
endl
: It inserts a new line and flushes the output stream.
So eventually
cout<<endl;
is equivalent to using
cout<<'\n'<<flush;
Conclusion
Using '\n'
outperforms endl
in terms of speed (or time) when matter is related to new line only.
Related Problem
The problem which I solved and got TLE issue was Escape from Stones. Go and have a shot at it.
Why down-votes? seems useful to me.
Thanks. I appreciate it. Don't know how blogs work here but I will keep posting stuff I find helpful.
I guess some people down-vote based on colour, or they feel things like these are too basic (even though a lot of people don't know about it). Anyways, keep posting!
Sure. Thanks.
Heck just put
#define endl '\n'
at the beginning of the codeHave a nice time fixing IL1 in interactive problems
Then comment the line!
Well, you will never remember that untill you get IL) So it will cost you 20 minutes every time you solve an interactive problem. I don't think your teammates will appreciate that kind of a performance))
Well, you can remember to write
cout.flush()
when you solve interactive problems.This doesn't help. I don't understand why, but sometimes you'll still get IL 1. Check 44326991 for an example (differs from 44326589 only in the line with define)
I suppose, it's because you has used the
speedup
define. It disables sync with stdio.Wow that's incredible!!!
I always define this, but never had any problem with interactive problems, but why??
If you don't use
ios_base::sync_with_stdio(false)
cout
will be flushed after any output regardless.And even if you use previous command, but don't use
cin.tie(nullptr)
cout
will be flushed before any read fromcin
. And in the most of interactive problems you write something to output and then immediately read the answer from input.So for making bufferization fully work (and by this speeding up your I/O) you need to use all three things in your template (this two +
#define endl '\n'
), not just one. And if you use all three, interactive problems won't work.I just put
const char en='\n';
and use en instead of endl in non-interactive problems.Here is Another problem where you face requirement of '\n' instead of endl. Same submission of mine got TLE with endl and got accepted with '\n'