Last round I submitted problem D using cin/cout + ios::sync_with_stdio(false) but it turned out to be too slow (TLE on test 3). Then I try to put cin.tie(0) and got Accepted in 2 seconds. Anyone have any idea why cin.tie(0) is necessary in this case ?
My submissions:
http://codeforces.com/contest/546/submission/11225195
http://codeforces.com/contest/546/submission/11224645
UPD: Explained by rlac and alternative fix by vadimmm in the comment below.
Iostream=evil. You never know when will bring.
By default, before you call the function
cin
, the callcout << flush
is done. So, in your first submission there isn't any difference betweencout << endl
andcout << "\n"
.You can override this behavior by calling the function
cin.tie(0)
.I hope this can help you
what is cout<<flush
It forces the output buffer to be flushed. When you say
cout << X
,X
isn't automatically printed automatically to the console, it is stored in a buffer and then, when the buffer is flushed is that actually X is printed in the console (this is what actually makes output operations to be slow).Hello rlac and NPA
cin.tie
did not help me.See this submission without
cin.tie
:TLE
11228080
This one is with
cin.tie
:TLE
11228099
And this one is with scanf/printf:
Accepted
11228062
I think your sieve is too slow (see the runtime of test 1 and test 2).
Try adding
ios::sync_with_stdio(false)
as well (in the same place ascin.tie(0)
).Nice explanation !
Thanks, now it seems that cin.tie(0) should always be included in the code.
Omg, I've always been using iostream without knowing this :o. One can learn something even in Div2 contests, I see :P.
If you write
some_stream.tie(ostream_ptr)
, the tied output stream (references byostream_ptr
) is flushed before each i/o operation insome_stream
.By default
std::cin
andstd::cerr
are tied tostd::cout
.So avoid alternation of input and output (11226406), or use
std::cin.tie(nullptr)
.Thank you for your help, I learned a lot from your comment.
Also scanf and printf are faster compared to iostream. It depends on the compiler but that's the case in codeforces.
A lot of people in round's blog's comment section also talks about it. And it really annoys me. Please stop.
Your solution is not as fast as the intended one, don't blame cin/cout or authors.
It's just silly.
UPD: I'm sorry. I was wrong. It turns out that even intended solution gets TLE because of it.
I just wanna know why my code failed :|
I know. It wasn't something personal. It was general and I thought this blog would be better for everyone to see it. I was wrong anyway.