Hello guys, yesterday I was solving the problem RAJAPRO and was trying out a new template.
But I noticed something unusual(at least to me :p). Both the submissions have same code except in the first one I used scanf for input while in second one I used cin.
The difference in execution time was too high and I was amazed cz I thought scanf takes less time for input as compared to cin!!
Can anyone provide a valid justification to this and tell which one is faster?
Thanks
Its true that scanf() is faster than cin because cin wastes time synchronizing itself with the stdio buffer.But turning off synchronization of all the iostream standard streams with stdio will make cin faster than scanf().
Read this article for more details.
Now in your link1 you have used scanf and cout and in link2 you have used cin,cout and turned off synchronization which makes both cin and cout faster but in first case you have used cout without truning off the synchronization.
So I think both these factor makes your program 1 run slower than the second.
scanf and printf are indeed faster compared to cin and cout. In fact, the difference is especially visible in codeforces round.
If you use normal cin and cout when input is of magnitude ~{10}^{6} there, you will get TLE in taking input itself! (Speaking for Time limit of 2 seconds). This has resulted in many people failing real/large test cases there.
Even in JAVA, if you use scanner class, its possible that you may time out because its slow in taking input. A solution of scanner class taking ~3 seconds in JAVA takes only 0.75 seconds using Buffered Reader, further reduced fif you use user defined template for Faster I/O.
But in codeforces its seen that even cin/cout with synchronization off is slower than scanf printf. I once got tle even after turning off the synchronization , so its safe to use scanf/printf always.