In competitive programming, efficient handling of input and output operations plays a crucial role. There are scenarios where we may have to handle a small array with just five elements, while in other cases, the array size could be as large as 10,000. This is where the significance of speedy input/output operations becomes evident.
Now let us discuss some useful tips beneficial to avoid the TLE -
- For taking a value as input, the general format in C++ is - std::cin>>x; // x the value to be input The cin works better for a range of inputs but it is convenient to use - scanf('%d",&x); // x is the value to be input Similarly, for printing on the console we use - Std::cout<<x ; // x is the value to be printed The cout also works fine for limited numbers. The best practice is using- printf("%d", x); // x is the value to be printed
- To gain the same speed of scanf/printf with cin/cout. Add the below lines in the main function - iosbase::syncwith_stdio(false) - It toggles all the synchronization of all C++ with their respective C streams when called before cin/cout in a program. We make this function false(which is true earlier) to avoid any synchronization. cin. tie(NULL) - The function helps to flush all the std::cout before any input is taken. It is beneficial in interactive console programs in which the console is updated regularly but also slows down the program for larger values. NULL refers to returning a null pointer.
- Include a header file that contains all the others libraries. It is a standard header for the GNU C++ library. Including the below header file saves time and the effort to add a particular library for a data structure. For example, for declaring a map we need a header file. This extra effort is reduced which is also time saving. #include This is how a common C++ program template looks on applying the tips:
#include <bits/stdc++.h> // GNU header
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL); // flushes cout
return 0;
}
- Using the escape sequence "\n" is recommended for moving to a new line over endl. While "\n" simply moves to a new line, endl not only moves to a new line but also flushes the stream. Hence, cout<<endl is equivalent to cout<<"\n" << flush.
Differences between "\n" and endl
| endl | \n |
|---|---|
| Manipulator | Character |
| Does not occupy memory | Occupy memory of 1 byte |
| endl is a keyword. So it won't give meaning when stored in a string | \n can be stored in a string |
| Supported only by C++ | Supported by both |