Skip to main content

Documentation Index

Fetch the complete documentation index at: https://resources.devweekends.com/llms.txt

Use this file to discover all available pages before exploring further.

CP Environment Setup

The Perfect CP Setup

A fast, efficient environment is crucial for competitive programming. Every second matters in contests. This guide covers everything from VS Code configuration to templates and workflow optimization.

VS Code Setup for CP

Essential Extensions

Install these extensions for the best CP experience:
ExtensionPurposeID
C/C++IntelliSense, debuggingms-vscode.cpptools
Code RunnerQuick executionformulahendry.code-runner
Competitive Programming HelperParse problemsDivyanshuAgrawal.competitive-programming-helper
Error LensInline errorsusernamehw.errorlens

VS Code Settings for CP

Add to your settings.json (Ctrl+Shift+P → “Open Settings JSON”):
{
    // C++ specific settings
    "C_Cpp.default.cppStandard": "c++17",
    "C_Cpp.default.compilerPath": "g++",
    
    // Code Runner settings
    "code-runner.executorMap": {
        "cpp": "cd $dir && g++ -std=c++17 -O2 -Wall -Wextra -Wshadow -o $fileNameWithoutExt $fileName && $dir$fileNameWithoutExt < input.txt"
    },
    "code-runner.runInTerminal": true,
    "code-runner.saveFileBeforeRun": true,
    "code-runner.clearPreviousOutput": true,
    
    // Editor settings for speed
    "editor.formatOnSave": false,
    "editor.minimap.enabled": false,
    "editor.fontSize": 14,
    "editor.wordWrap": "on",
    
    // File associations
    "files.associations": {
        "*.cpp": "cpp"
    },
    
    // Terminal settings
    "terminal.integrated.fontSize": 13
}

Keyboard Shortcuts

Add to keybindings.json (Ctrl+Shift+P → “Open Keyboard Shortcuts JSON”):
[
    {
        "key": "ctrl+alt+n",
        "command": "code-runner.run"
    },
    {
        "key": "ctrl+alt+c",
        "command": "code-runner.stop"
    },
    {
        "key": "ctrl+shift+t",
        "command": "workbench.action.terminal.toggleTerminal"
    }
]

Folder Structure

Organize your CP workspace:
competitive-programming/
├── templates/
│   ├── template.cpp
│   ├── template_interactive.cpp
│   └── snippets.cpp
├── codeforces/
│   ├── contest_1900/
│   │   ├── A.cpp
│   │   ├── B.cpp
│   │   └── input.txt
│   └── practice/
├── cses/
├── atcoder/
└── library/
    ├── data_structures/
    ├── graphs/
    ├── math/
    └── strings/

The Ultimate CP Template

Standard Template

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

// Type aliases
using ll = long long;
using ull = unsigned long long;
using ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vi = vector<int>;
using vll = vector<ll>;
using vvi = vector<vi>;
using vvll = vector<vll>;

// Constants
const int MOD = 1e9 + 7;
const int MOD2 = 998244353;
const ll INF = 1e18;
const int IINF = 1e9;
const ld PI = acosl(-1.0);
const ld EPS = 1e-9;

// Macros
#define endl '\n'
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) (int)(x).size()
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define fi first
#define se second
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define FORR(i, a, b) for (int i = (a); i >= (b); i--)
#define rep(i, n) FOR(i, 0, n)
#define repr(i, n) FORR(i, n - 1, 0)

// Debug (comment out before submission)
#ifdef LOCAL
#define debug(x) cerr << #x << " = " << x << endl
#define debugv(v) cerr << #v << " = "; for(auto& x : v) cerr << x << " "; cerr << endl
#else
#define debug(x)
#define debugv(v)
#endif

// Input/Output
template<typename T> void read(T& x) { cin >> x; }
template<typename T, typename... Args> void read(T& x, Args&... args) { cin >> x; read(args...); }
template<typename T> void print(const T& x) { cout << x << endl; }
template<typename T, typename... Args> void print(const T& x, Args... args) { cout << x << " "; print(args...); }

// Read vector
template<typename T> vector<T> readv(int n) {
    vector<T> v(n);
    for (auto& x : v) cin >> x;
    return v;
}

// Utility functions
template<typename T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; }
template<typename T> T lcm(T a, T b) { return a / gcd(a, b) * b; }
template<typename T> T power(T a, T b, T mod) {
    T res = 1; a %= mod;
    while (b > 0) {
        if (b & 1) res = res * a % mod;
        a = a * a % mod; b >>= 1;
    }
    return res;
}
template<typename T> bool chmin(T& a, T b) { return b < a ? a = b, true : false; }
template<typename T> bool chmax(T& a, T b) { return b > a ? a = b, true : false; }

// Direction arrays for grid problems
const int dx[] = {0, 0, 1, -1, 1, 1, -1, -1};
const int dy[] = {1, -1, 0, 0, 1, -1, 1, -1};

void solve() {
    // Your solution here
    
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int t = 1;
    cin >> t;  // Comment out for single test case
    
    while (t--) {
        solve();
    }
    
    return 0;
}

Specialized Templates

Interactive Problems Template

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

void solve() {
    int n;
    cin >> n;
    
    // Example: Binary search interactive
    int lo = 1, hi = n;
    
    while (lo < hi) {
        int mid = (lo + hi) / 2;
        
        cout << "? " << mid << endl;  // Query
        cout.flush();  // IMPORTANT: Flush after each query
        
        int response;
        cin >> response;
        
        if (response == 1) {
            hi = mid;
        } else {
            lo = mid + 1;
        }
    }
    
    cout << "! " << lo << endl;  // Final answer
    cout.flush();
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int t = 1;
    cin >> t;
    
    while (t--) {
        solve();
    }
    
    return 0;
}
Interactive Problem Rules:
  1. Always flush after each output: cout.flush() or endl
  2. Don’t print extra output
  3. Read the response before the next query
  4. Some judges require \n instead of endl

Multi-Test with Global Reset

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

const int MAXN = 2e5 + 5;

// Global arrays (reset before each test)
int n, m;
vector<int> adj[MAXN];
bool visited[MAXN];
int dist[MAXN];

void reset() {
    for (int i = 0; i <= n; i++) {
        adj[i].clear();
        visited[i] = false;
        dist[i] = 0;
    }
}

void solve() {
    cin >> n >> m;
    reset();  // Reset globals
    
    for (int i = 0; i < m; i++) {
        int u, v;
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    
    // Solution...
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int t;
    cin >> t;
    
    while (t--) {
        solve();
    }
    
    return 0;
}

Input/Output Patterns

Reading Different Input Formats

// Single line of space-separated integers
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];

// Or using the template function
auto a = readv<int>(n);

// Matrix input
int n, m;
cin >> n >> m;
vector<vector<int>> grid(n, vector<int>(m));
for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
        cin >> grid[i][j];

// Character grid
vector<string> grid(n);
for (int i = 0; i < n; i++) cin >> grid[i];

// Graph (adjacency list)
int n, m;
cin >> n >> m;
vector<vector<int>> adj(n + 1);
for (int i = 0; i < m; i++) {
    int u, v;
    cin >> u >> v;
    adj[u].push_back(v);
    adj[v].push_back(u);
}

// Weighted graph
vector<vector<pair<int, int>>> adj(n + 1);
for (int i = 0; i < m; i++) {
    int u, v, w;
    cin >> u >> v >> w;
    adj[u].push_back({v, w});
    adj[v].push_back({u, w});
}

// Read until EOF
int x;
while (cin >> x) {
    // Process x
}

Output Patterns

// Print vector
for (int x : v) cout << x << " ";
cout << endl;

// Print with custom separator
for (int i = 0; i < n; i++) {
    cout << a[i] << " \n"[i == n - 1];  // Space except last, then newline
}

// Print YES/NO
cout << (condition ? "YES" : "NO") << endl;

// Print with precision
cout << fixed << setprecision(9) << answer << endl;

// Print matrix
for (auto& row : grid) {
    for (int x : row) cout << x << " ";
    cout << endl;
}

Stress Testing Script

stress.cpp

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

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

int randint(int lo, int hi) {
    return uniform_int_distribution<int>(lo, hi)(rng);
}

void generateTest() {
    int n = randint(1, 10);
    cout << n << endl;
    for (int i = 0; i < n; i++) {
        cout << randint(1, 100) << " \n"[i == n - 1];
    }
}

int main() {
    // Generate random test
    generateTest();
    return 0;
}

stress.bat (Windows)

@echo off
g++ -std=c++17 -O2 solution.cpp -o solution.exe
g++ -std=c++17 -O2 brute.cpp -o brute.exe
g++ -std=c++17 -O2 stress.cpp -o stress.exe

:loop
stress.exe > input.txt
solution.exe < input.txt > output1.txt
brute.exe < input.txt > output2.txt

fc output1.txt output2.txt > nul
if errorlevel 1 (
    echo MISMATCH FOUND!
    type input.txt
    pause
    exit
)

echo Test passed
goto loop

stress.sh (Linux/Mac)

#!/bin/bash
g++ -std=c++17 -O2 solution.cpp -o solution
g++ -std=c++17 -O2 brute.cpp -o brute
g++ -std=c++17 -O2 stress.cpp -o stress

for ((i = 1; ; i++)); do
    ./stress > input.txt
    ./solution < input.txt > output1.txt
    ./brute < input.txt > output2.txt
    
    if ! diff -q output1.txt output2.txt > /dev/null; then
        echo "Mismatch on test $i!"
        cat input.txt
        echo "Expected:"
        cat output2.txt
        echo "Got:"
        cat output1.txt
        exit 1
    fi
    
    echo "Test $i passed"
done

Compile Commands

Standard Compilation

# Basic compilation
g++ -std=c++17 -o solution solution.cpp

# With optimizations (for local testing)
g++ -std=c++17 -O2 -o solution solution.cpp

# With all warnings (for debugging)
g++ -std=c++17 -Wall -Wextra -Wshadow -o solution solution.cpp

# With debug symbols (for gdb)
g++ -std=c++17 -g -o solution solution.cpp

# With sanitizers (find bugs)
g++ -std=c++17 -fsanitize=address,undefined -o solution solution.cpp

# Full debug mode
g++ -std=c++17 -DLOCAL -Wall -Wextra -Wshadow -fsanitize=address,undefined -g -o solution solution.cpp

tasks.json for VS Code

Create .vscode/tasks.json:
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "CP: Build",
            "type": "shell",
            "command": "g++",
            "args": [
                "-std=c++17",
                "-O2",
                "-Wall",
                "-Wextra",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        },
        {
            "label": "CP: Build & Run",
            "type": "shell",
            "command": "g++ -std=c++17 -O2 ${file} -o ${fileDirname}/${fileBasenameNoExtension} && ${fileDirname}/${fileBasenameNoExtension} < ${fileDirname}/input.txt",
            "group": "build"
        },
        {
            "label": "CP: Debug Build",
            "type": "shell",
            "command": "g++",
            "args": [
                "-std=c++17",
                "-DLOCAL",
                "-Wall",
                "-Wextra",
                "-Wshadow",
                "-fsanitize=address,undefined",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "group": "build"
        }
    ]
}

VS Code Snippets

Create .vscode/cpp.json or add to User Snippets:
{
    "CP Template": {
        "prefix": "cptemplate",
        "body": [
            "#include <bits/stdc++.h>",
            "using namespace std;",
            "",
            "using ll = long long;",
            "using pii = pair<int, int>;",
            "using vi = vector<int>;",
            "",
            "#define endl '\\n'",
            "#define all(x) (x).begin(), (x).end()",
            "#define sz(x) (int)(x).size()",
            "",
            "const int MOD = 1e9 + 7;",
            "const ll INF = 1e18;",
            "",
            "void solve() {",
            "    $0",
            "}",
            "",
            "int main() {",
            "    ios::sync_with_stdio(false);",
            "    cin.tie(nullptr);",
            "    ",
            "    int t = 1;",
            "    cin >> t;",
            "    ",
            "    while (t--) {",
            "        solve();",
            "    }",
            "    ",
            "    return 0;",
            "}"
        ],
        "description": "Competitive Programming Template"
    },
    "Read Vector": {
        "prefix": "readv",
        "body": [
            "int ${1:n};",
            "cin >> ${1:n};",
            "vector<${2:int}> ${3:a}(${1:n});",
            "for (auto& x : ${3:a}) cin >> x;"
        ],
        "description": "Read vector input"
    },
    "For Loop": {
        "prefix": "fori",
        "body": [
            "for (int ${1:i} = 0; ${1:i} < ${2:n}; ${1:i}++) {",
            "    $0",
            "}"
        ],
        "description": "For loop"
    },
    "BFS Template": {
        "prefix": "bfs",
        "body": [
            "queue<int> q;",
            "vector<int> dist(n + 1, -1);",
            "q.push(${1:start});",
            "dist[${1:start}] = 0;",
            "",
            "while (!q.empty()) {",
            "    int u = q.front();",
            "    q.pop();",
            "    ",
            "    for (int v : adj[u]) {",
            "        if (dist[v] == -1) {",
            "            dist[v] = dist[u] + 1;",
            "            q.push(v);",
            "        }",
            "    }",
            "}"
        ],
        "description": "BFS template"
    },
    "DFS Template": {
        "prefix": "dfs",
        "body": [
            "vector<bool> visited(n + 1, false);",
            "",
            "function<void(int)> dfs = [&](int u) {",
            "    visited[u] = true;",
            "    for (int v : adj[u]) {",
            "        if (!visited[v]) {",
            "            dfs(v);",
            "        }",
            "    }",
            "};",
            "",
            "dfs(${1:1});"
        ],
        "description": "DFS template with lambda"
    },
    "Binary Search": {
        "prefix": "binsearch",
        "body": [
            "int lo = ${1:0}, hi = ${2:n};",
            "while (lo < hi) {",
            "    int mid = lo + (hi - lo) / 2;",
            "    if (${3:condition}) {",
            "        hi = mid;",
            "    } else {",
            "        lo = mid + 1;",
            "    }",
            "}",
            "// lo is the answer"
        ],
        "description": "Binary search template"
    },
    "Dijkstra": {
        "prefix": "dijkstra",
        "body": [
            "vector<ll> dist(n + 1, INF);",
            "priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<>> pq;",
            "",
            "dist[${1:start}] = 0;",
            "pq.push({0, ${1:start}});",
            "",
            "while (!pq.empty()) {",
            "    auto [d, u] = pq.top();",
            "    pq.pop();",
            "    ",
            "    if (d > dist[u]) continue;",
            "    ",
            "    for (auto [v, w] : adj[u]) {",
            "        if (dist[u] + w < dist[v]) {",
            "            dist[v] = dist[u] + w;",
            "            pq.push({dist[v], v});",
            "        }",
            "    }",
            "}"
        ],
        "description": "Dijkstra's algorithm"
    },
    "DSU": {
        "prefix": "dsu",
        "body": [
            "struct DSU {",
            "    vector<int> parent, rank_;",
            "    DSU(int n) : parent(n + 1), rank_(n + 1, 0) {",
            "        iota(parent.begin(), parent.end(), 0);",
            "    }",
            "    int find(int x) {",
            "        if (parent[x] != x) parent[x] = find(parent[x]);",
            "        return parent[x];",
            "    }",
            "    bool unite(int x, int y) {",
            "        int px = find(x), py = find(y);",
            "        if (px == py) return false;",
            "        if (rank_[px] < rank_[py]) swap(px, py);",
            "        parent[py] = px;",
            "        if (rank_[px] == rank_[py]) rank_[px]++;",
            "        return true;",
            "    }",
            "};"
        ],
        "description": "Disjoint Set Union"
    },
    "Segment Tree": {
        "prefix": "segtree",
        "body": [
            "struct SegTree {",
            "    int n;",
            "    vector<ll> tree;",
            "    ",
            "    SegTree(int n) : n(n), tree(4 * n, 0) {}",
            "    ",
            "    void update(int node, int start, int end, int idx, ll val) {",
            "        if (start == end) {",
            "            tree[node] = val;",
            "            return;",
            "        }",
            "        int mid = (start + end) / 2;",
            "        if (idx <= mid) update(2*node, start, mid, idx, val);",
            "        else update(2*node+1, mid+1, end, idx, val);",
            "        tree[node] = tree[2*node] + tree[2*node+1];",
            "    }",
            "    ",
            "    ll query(int node, int start, int end, int l, int r) {",
            "        if (r < start || end < l) return 0;",
            "        if (l <= start && end <= r) return tree[node];",
            "        int mid = (start + end) / 2;",
            "        return query(2*node, start, mid, l, r) +",
            "               query(2*node+1, mid+1, end, l, r);",
            "    }",
            "    ",
            "    void update(int idx, ll val) { update(1, 0, n-1, idx, val); }",
            "    ll query(int l, int r) { return query(1, 0, n-1, l, r); }",
            "};"
        ],
        "description": "Segment Tree"
    }
}

Online Judge Tools

Competitive Companion (Browser Extension)

  1. Install Competitive Companion for Chrome/Firefox
  2. It automatically parses problem statements and test cases
  3. Works with Codeforces, AtCoder, CSES, and more

cp-tools for VS Code

Use with Competitive Programming Helper extension:
  1. Click on the problem in browser with Competitive Companion
  2. Test cases auto-download to your workspace
  3. Run all test cases with one click

Quick Reference Card

Complexity Limits

nMax ComplexityOperations
10O(n!)~3.6M
20O(2^n)~1M
100O(n³)~1M
500O(n³)~125M
3000O(n²)~9M
10^5O(n log n)~1.7M
10^6O(n)~1M
10^9O(log n)~30

Common Mistakes Checklist

  • Integer overflow → Use long long
  • Array out of bounds → Check indices
  • Uninitialized variables → Initialize everything
  • Wrong loop bounds → Off-by-one errors
  • Forgot to reset globals → Clear between test cases
  • TLE → Check complexity, optimize I/O
  • WA on edge cases → Test n=0, n=1, negative numbers

Key Takeaways

Fast I/O

Always use ios::sync_with_stdio(false) and cin.tie(nullptr).

Templates Save Time

Have snippets ready for common patterns.

Stress Test

Generate random tests to find edge cases.

Debug Locally

Use -DLOCAL flag for debug output.

Next Up

Chapter 3: STL Mastery

Master the Standard Template Library for competitive programming.

Interview Deep-Dive

Strong Answer:
  • Templates eliminate repetitive boilerplate that wastes time and introduces bugs under contest pressure. Fast I/O setup, type aliases, common macros, and debug utilities are identical across problems — typing them from scratch each time is pure waste.
  • For solo contests, maximize personal convenience: heavy macro usage, short aliases, everything you personally know. For ICPC team contests, the template must be readable by all three team members. I would reduce macros to the universally understood ones (all, sz, pb), keep type aliases standard (ll, vi, pii), and ensure the debug system compiles out cleanly with the LOCAL flag.
  • The template should include: fast I/O, type aliases, a solve() function with test case loop, debug macros gated behind LOCAL, and direction arrays for grid problems. It should NOT include: algorithm implementations (segment tree, DSU) — those belong in a separate code library that you copy when needed.
  • A good template is under 40 lines. Longer templates slow down compilation, increase the chance of IDE errors, and make it harder to find your actual solution code during debugging.
Follow-up: What compiler flags should be in your default build configuration, and why?-std=c++17 for structured bindings and if-constexpr. -O2 for optimization (matches most online judges). -Wall -Wextra -Wshadow for catching bugs at compile time — shadowed variables are a common source of subtle bugs. -DLOCAL for enabling debug macros. For debugging sessions specifically: -fsanitize=address,undefined to catch memory errors and undefined behavior. For stress testing: -O2 without sanitizers for speed. I maintain two build tasks in VS Code: “Build (Debug)” with sanitizers and “Build (Submit)” with just O2.
Strong Answer:
  • AddressSanitizer (ASan) is a runtime tool that detects memory errors: out-of-bounds array access, use-after-free, stack buffer overflow, heap buffer overflow, and memory leaks. It instruments every memory access with bounds checks and maintains a shadow memory map to track which bytes are valid.
  • Concrete example: you declare int arr[100] and somewhere in a loop you write to arr[100] (one past the end). Without ASan, this silently overwrites whatever is next in memory — maybe another variable, maybe the return address. Your program might produce a wrong answer, crash randomly, or appear to work correctly (the most dangerous outcome because you submit a buggy solution).
  • With ASan, the program immediately crashes with a detailed error message showing the exact line number, the invalid address, and the allocated buffer it tried to access past. Instead of spending 30 minutes tracking down a mysterious WA, you fix it in 30 seconds.
  • Runtime overhead: ASan slows execution by about 2x and increases memory usage by 2-3x. This means you should NOT use it on the actual submission (the online judge does not have it enabled and the overhead might cause TLE). Use it for local testing only, then compile without it for submission.
Follow-up: What about UndefinedBehaviorSanitizer — what does it catch that ASan does not?UBSan catches undefined behavior that does not involve memory access: signed integer overflow (the number one CP bug), division by zero, null pointer dereference, shift operations by negative or too-large amounts, and misaligned pointer access. The key one for CP is signed overflow: int a = 1e9; int b = a * 2; is undefined behavior in C++ (the result exceeds INT_MAX). Without UBSan, this silently wraps around to a garbage value. With UBSan, you get an immediate error message pinpointing the line. Use both together: -fsanitize=address,undefined.
Strong Answer:
  • Minute 1-3: Install g++ (via MinGW on Windows or build-essential on Linux). Verify with g++ --version. This is the non-negotiable prerequisite.
  • Minute 4-7: Create a single template file with fast I/O, the solve() function with test case loop, using ll = long long, and basic macros. Save it to a known location. Show them how to copy it to start a new problem.
  • Minute 8-10: Create an input.txt file in the same directory. Show them the workflow: paste sample input into input.txt, compile with g++ -O2 -o sol sol.cpp, run with ./sol < input.txt. This is the fastest possible feedback loop.
  • Minute 11-13: Set up VS Code with the Code Runner extension configured to compile and run against input.txt with a single keyboard shortcut (Ctrl+Alt+N). Show them how to switch between problems by editing input.txt.
  • Minute 14-15: Walk through one complete cycle: open template, read a problem, edit solve(), paste sample into input.txt, press the run shortcut, verify output matches expected. Confirm they can do this independently.
  • What I explicitly skip: debug macros (too confusing for beginners), stress testing setup (premature), VS Code snippets (add later), and Competitive Companion (add after they are comfortable with manual input). Keep the initial setup minimal so they are not overwhelmed.
Follow-up: What do you add in the second session, after they have done their first contest?Debug macros with the LOCAL flag, a pre-submit checklist (overflow, bounds, reset, format), and the Competitive Companion browser extension for automatic test case parsing. After their first contest, they will have experienced specific pain points (slow input parsing, difficulty comparing output, forgetting edge cases) and the additions will feel motivated rather than arbitrary.