1. Allocating
Refrain from declaring big arrays as local variables, as it will often cause you to run out of stack space and fail with a Runtime Error.
Instead of doing:
int main()
{
int N;
scanf("%d", &N);
int arr[N];
for(int i = 0; i < N; i++) scanf("%d", &arr[i]);
}
consider:
int arr[100001];
int main()
{
int N;
scanf("%d", &N);
for(int i = 0; i < N; i++) scanf("%d", &arr[i]);
}
Declaring big arrays in global scope is a much safer approach as long as you know the maximum bound of ~N~ (and almost all problems give you upper bounds). Be wary of out of bounds array indices, though.
2. Input and Output
It is recommended for C++ users to use C-style input and output, namely scanf
and printf
instead of cin
and cout
for performance reasons.
If you must use cin
and cout
, you can put these two lines of code at the top of your main
function:
int main()
{
cin.sync_with_stdio(0);
cin.tie(0);
...
}
to speed up the cin
stream. This will unsync cin
with scanf
and cout
. Note that you should not use scanf
after unsyncing with stdio
.
Additionally, you should not use endl
, but rather \n
to output newlines when flushing is not required. endl
's flushing behavior can potentially cause your program to receive TLE instead of AC.
Finally, if the problem only requires unsigned integral data types to be read, you can prepend this macro to the top of your source:
#define scan(x) do{while((x=getchar())<'0'); for(x-='0'; '0'<=(_=getchar()); x=(x<<3)+(x<<1)+_-'0');}while(0)
char _;
Instead of std::cin >> n
, or scanf("%d", &n)
, you would use scan(n)
.
3. int
, long
, and long long
On the judge, int
is 32-bit, long long
is 64-bit, and long
can be either 32- or 64-bit depending on which judge your submission is graded on. Therefore, it is recommended to use either int
or long long
, but not long
.