Basics
C++ code template
A typical C++ code template for competitive programming
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
#define fastio() ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
int32_t main() {
fastio();
// Solution comes here
return 0;
}
Input/Output (IO)
int a, b;
string x;
cin >> a >> b >> x;
int a = 123, b = 456;
string x = "monkey";
cout << a << " " << b << " " << x << "\n";
- Sometimes the program should read a whole line from the input, possibly containing spaces. This can be accomplished by using the getline function:
string s;
getline(cin, s);
Working with numbers
-
Integers
In competitive programming, the most common integer type is
int
(32-bit), with a range of about ±2×10⁹. For larger numbers, uselong long
(64-bit), which supports values up to ±9×10¹⁸.Be careful with mixed-type arithmetic — for example:
int a = 123456789; long long b = a * a; // Wrong! Still computed as int long long b = (long long)a * a; // Correct
Although __int128_t (128-bit) exists in g++, it’s rarely needed and not supported on all platforms. Usually, long long is sufficient for most contest problems.
-
Modular arithmetic
We use
x mod m
to mean the remainder whenx
is divided bym
. For example:In contests, when answers are very large, it’s common to output them modulo m (e.g.,
10^9 + 7
) to keep values manageable and avoid overflow.Key Properties: Mod can be safely applied before or after arithmetic operations:
(a + b) % m = ((a % m) + (b % m)) % m
(a - b) % m = ((a % m) - (b % m)) % m
(a * b) % m = ((a % m) * (b % m)) % m
This ensures intermediate results stay small.
Example: Factorial Modulo
m
long long x = 1; for (int i = 2; i <= n; i++) { x = (x * i) % m; } cout << x << "\n";
Handling Negative Mods In C++ and many languages, a negative result can occur with subtraction. Fix it like this:
x = x % m; if (x < 0) x += m;
This ensures the result is always in the range 0 … m - 1
-
Floating point numbers
…
-
Shortening code
-
Type names
To simplify long or complex type names, use the
typedef
keyword. For example,long long
can be shortened toll
:typedef long long ll; ll a = 123456789; ll b = 987654321; cout << a * b << "\n"; typedef vector<int> vi; typedef pair<int, int> pi; vi nums = {1, 2, 3}; pi point = {4, 5};
-
Macros
…
-
-
Mathematics
…