Help With C++ IO

I have recently been getting TLEs in several contest problems and after seeing others I realized that some of the problems are due to my slow input / output.

Can someone provide me some tips to fasten IO in C++?

I already use ios_base::sync_with_stdio(0) , cin.tie(0), cout.tie(0) and "\n" instead of endl. What should I do apart from this?

1 Like

int32_t main() instead of int main() :slight_smile:

Also if you’re are getting TLE, you should work on your Algorithm, try to optimize it. Personally I think Fast IO is not that important if you have the correct optimized algorithm.

1 Like

If you use C-style print functions,

Include <unistd.h>. Print strings via fputs_unlocked("hello",stdout) and its friends.

Buffer often, print rarely.


If you are getting TLE after including all this.So the reason may be you are using brute force solution instead of some optimized one.
Try to analyze the constraints and then look for your solution.

1 Like

this i think won’t get the IO faster since int32_t you specifying is just same as int.
if you look in the file stdint.h or say cstdint the implementation of int32_t goes as

typedef int int32_t

and so this makes no difference

you need to come up with a better algorithm to solve the problem, fast IO has nothing to do, sometimes it does but mostly the faster and optimized algorithms are more of the importance.

adding these line may only give you an advantage of may be a few mill second but not more than that. the most important thing if you are having input file where inputs generally exceed 10^5 then you should try to avoid N^2 complexity and try to come with an algorithm which has complexity say N, N*logN or something which is lower than that

some algorithms you can implement to reduce the time complexity are

Divide and Conquer
Greedy approach and many more.

Huh i don’t know any more because you know i recently started to program this very month.
Feel free to share any more queries

Try learning Algorithms and Data structure any try to implement them as much as possible. Instead of using brute force approach use standard approach for standard question . Check Question constraints properly . Avoid O(n^2) O(0^3) as much as possible . try to optimize your code .

Happy coding …

Your answer is no way related to the question. The question is on fast I/O and not on efficient algorithms.:slightly_smiling_face:

Theres fast IO in c++ but most of the times if u r getting TLE in c++ despite using cin.tie then it means that ur approach is wrong
think of better algo, DS