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:| Extension | Purpose | ID |
|---|---|---|
| C/C++ | IntelliSense, debugging | ms-vscode.cpptools |
| Code Runner | Quick execution | formulahendry.code-runner |
| Competitive Programming Helper | Parse problems | DivyanshuAgrawal.competitive-programming-helper |
| Error Lens | Inline errors | usernamehw.errorlens |
VS Code Settings for CP
Add to yoursettings.json (Ctrl+Shift+P → “Open Settings JSON”):
Copy
{
// 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 tokeybindings.json (Ctrl+Shift+P → “Open Keyboard Shortcuts JSON”):
Copy
[
{
"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:Copy
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
Copy
#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
Copy
#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:
- Always flush after each output:
cout.flush()orendl - Don’t print extra output
- Read the response before the next query
- Some judges require
\ninstead ofendl
Multi-Test with Global Reset
Copy
#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
Copy
// 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
Copy
// 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
Copy
#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)
Copy
@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)
Copy
#!/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
Copy
# 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:
Copy
{
"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:
Copy
{
"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)
- Install Competitive Companion for Chrome/Firefox
- It automatically parses problem statements and test cases
- Works with Codeforces, AtCoder, CSES, and more
cp-tools for VS Code
Use with Competitive Programming Helper extension:- Click on the problem in browser with Competitive Companion
- Test cases auto-download to your workspace
- Run all test cases with one click
Quick Reference Card
Complexity Limits
| n | Max Complexity | Operations |
|---|---|---|
| 10 | O(n!) | ~3.6M |
| 20 | O(2^n) | ~1M |
| 100 | O(n³) | ~1M |
| 500 | O(n³) | ~125M |
| 3000 | O(n²) | ~9M |
| 10^5 | O(n log n) | ~1.7M |
| 10^6 | O(n) | ~1M |
| 10^9 | O(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.