The issue is somehow related to the usage of the printf call in the presence of the
<iostream> header (part of the bits/stdc++.h include).
For example, if you add fflush(stdout); at the end of you main program, you will get a correct solution regardless of whether you include
The overall recommendation would be to use cin and cout in C++ programs since cin and cout have type-safe checks as compared with scanf and printf. scanf and printf (along with stdio.h) are remnants of the early days of C programming. Unless you are into embedded programming as your career, it makes sense to deal with C++ paradigms. Furthermore, if you consider competitive programming as a preparation for job hunting and interviews, the cin/cout approach definitely beats scanf/printf. Just compare:
cin >> a[i];
cout << ans << “\n”;
If you need faster IO with cin and cout, you can add
at the beginning of your main program. The relative performance of data reading is the following (the measurements are done on HackerRank servers but CodeChef servers are similar)
Reading 4,000,000 positive integer values, each less than 10^7:
- 1.55 sec - simple cin
- 0.51 sec - scanf
- 0.41 sec - cin with sync_with_stdio(false) and cin.tie(NULL)
There are ways to reduce it even further (to sub 0.1 sec levels) but it becomes somewhat esoteric in implementation.