CP template — fast I/O, macros & type aliases

RoadmapsC++

Scenario

You start a competitive programming contest. You spend the first 3 minutes typing `#include <iostream>`, `#include <vector>`, `using namespace std;`, and setting up `cin.tie(NULL)`. You've already lost time compared to higher-ranked competitors.

How do Grandmasters avoid writing the same 20 lines of boilerplate every single match?

Why it exists

In Competitive Programming, you are graded against a strict time limit (usually 1-2 seconds). Reading 1 million integers using standard synchronized `std::cin` can easily take 0.8 seconds, leaving almost no CPU time for your actual algorithm. CP templates exist to instantly inject I/O optimizations and shorthand aliases so you can focus entirely on the logic without hitting artificial timeouts.

Mental model

A CP template is like a chef's 'mise en place'. Before the cooking timer even starts, all the ingredients (tools, aliases, optimizations) are already chopped, measured, and placed exactly where you need them.

A CP (Competitive Programming) template is a standardized header block that you copy-paste at the start of every contest. It includes universal headers (like `<bits/stdc++.h>`), type aliases (like `using ll = long long;`), and standard fast I/O boilerplate to ensure your program reads input optimally without manual setup.

Explanation

**1. The Master Header:**

Instead of `#include <iostream>`, `#include <vector>`, etc., competitors use `#include <bits/stdc++.h>`. This is a non-standard GCC header that includes *every* standard library header at once. It slows down compilation slightly, but saves immense typing time during contests.

**2. Fast I/O Setup:**

By default, `std::cin` and `std::cout` are tied to C's `stdio` (printf/scanf) to allow mixing C and C++ I/O. This synchronization makes C++ I/O incredibly slow. `ios_base::sync_with_stdio(false);` unties C++ streams from C's `stdio`, making C++ streams vastly faster. However, because they now have independent buffering, mixing `cin`/`cout` with `scanf`/`printf` leads to unpredictable, interleaved output. `cin.tie(NULL);` does something entirely different: it unties `cin` from `cout`, preventing `cout` from automatically forcing an expensive buffer flush every time input is read.

**3. Type Aliases & Macros:**

`long long` is verbose. `using ll = long long;` saves typing.

Macros like `#define pb push_back` or `#define all(x) (x).begin(), (x).end()` are extremely common to compress algorithms into fewer keystrokes.

**Real-world Engineering vs. CP:**

While a CP template is essential for racing against a 2-hour clock, it is considered **terrible practice in production engineering**. `#include <bits/stdc++.h>` ruins build times and isn't portable. `#define` macros pollute the global namespace and make debugging impossible. Keep these tricks strictly for contests.

Code examples

A Standard CP Template

#include <bits/stdc++.h>
using namespace std;

// Type aliases for speed
using ll = long long;
using vi = vector<int>;
using vll = vector<ll>;

// Macros for common operations
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)

void solve() {
    int n;
    cin >> n;
    vi a(n);
    FOR(i, 0, n) cin >> a[i];
    
    sort(all(a));
    cout << a.back() << "\n";
}

int main() {
    // FAST I/O
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    int t = 1;
    cin >> t; // Read number of test cases
    while (t--) {
        solve();
    }
    return 0;
}

This template guarantees maximum I/O speed, provides shortcuts for vectors and sorting, and automatically wraps the logic in a multi-test-case loop.

Key points

Common mistakes

Recall questions

Questions & answers

A competitor includes the fast I/O lines in `main()`, but their program crashes or outputs garbage data because they used both `cin >> x` and `scanf("%d", &y)` sequentially. Why did this happen?

Because `ios_base::sync_with_stdio(false)` unties the internal buffering of C and C++ I/O streams. Mixing them after untying results in unpredictable interleaving of reads and writes.

Approach: Understand the side-effects of performance hacks.

A developer submits a solution with `std::cout << ans << std::endl;` inside a loop running 10^6 times. They get TLE. They change it to `std::cout << ans << "\n";` and pass. Why did this fix it?

`std::endl` forces a buffer flush to the operating system on every single iteration. `"\n"` simply adds a newline character to the buffer, allowing the stream to write to the OS in large, efficient chunks.

Approach: Identify I/O bottlenecks in tight loops.

Return to C++ Roadmap