C++
Module 32: C++ for Competitive ProgrammingAdvanced55 min read

Competitive Programming: Fast I/O, Two Pointers, Prefix Sums, DP & DSU

Accelerate competitive programming with ios::sync_with_stdio(false), prefix sums, two pointers, sliding window, bit tricks, DP, and Disjoint Set Union.

Key Takeaways & Core Concepts
  • Prefix Sums & Difference Arrays: O(1) range sums.
  • Two Pointers & Sliding Window: Reduce O(n²) to O(n).
  • Binary Search on Answer: Monotonic predicate search.

1. Fast I/O & CP Template

std::ios::sync_with_stdio(false); std::cin.tie(nullptr); and '\n' instead of std::endl prevent TLE on 10^5+ I/O lines.

1. Disjoint Set Union (DSU) with Path Compression
1#include <iostream>
2#include <vector>
3#include <numeric>
4
5struct DSU {
6 std::vector<int> p;
7 DSU(int n) : p(n) { std::iota(p.begin(), p.end(), 0); }
8 int find(int x) { return p[x] == x ? x : (p[x] = find(p[x])); }
9 void unite(int a, int b) { a = find(a); b = find(b); if (a != b) p[a] = b; }
10};
11
12int main() {
13 DSU dsu(5);
14 dsu.unite(0, 2); dsu.unite(2, 4);
15 std::cout << "0 & 4 connected? " << (dsu.find(0) == dsu.find(4) ? "Yes" : "No") << "\n";
16 return 0;
17}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
17 lines
Note: Path compression gives near-O(1) amortized union/find.

2. Essential CP Patterns

  • Prefix Sums & Difference Arrays: O(1) range sums.
  • Two Pointers & Sliding Window: Reduce O(n²) to O(n).
  • Binary Search on Answer: Monotonic predicate search.
  • Dynamic Programming (DP), Bit Manipulation (__builtin_popcount), Disjoint Set Union (DSU), and Dijkstra / BFS.
Practice & AssessmentC++ Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)