Common Snippets
Quick Notes
Section titled “Quick Notes”Đây là trang copy nhanh các mẫu code thường gặp. Các snippet cố tình ngắn, dễ sửa theo bài toán. Khi dùng trong production, thêm kiểm tra lỗi và test kỹ hơn.
Syntax
Section titled “Syntax”// Copy snippet, đổi tên biến theo bài toán.Fast IO
Section titled “Fast IO”std::ios::sync_with_stdio(false);std::cin.tie(nullptr);Binary Search
Section titled “Binary Search”int firstTrue(int lo, int hi){ while (lo < hi) { int mid = lo + (hi - lo) / 2; if (ok(mid)) hi = mid; else lo = mid + 1; } return lo;}std::vector<int> dist(n, -1);std::queue<int> q;dist[s] = 0;q.push(s);
while (!q.empty()) { int u = q.front(); q.pop(); for (int v : g[u]) { if (dist[v] == -1) { dist[v] = dist[u] + 1; q.push(v); } }}void dfs(int u){ seen[u] = true; for (int v : g[u]) { if (!seen[v]) dfs(v); }}Dijkstra
Section titled “Dijkstra”using P = std::pair<long long, int>;std::priority_queue<P, std::vector<P>, std::greater<P>> pq;dist[s] = 0;pq.push({0, s});
while (!pq.empty()) { auto [d, u] = pq.top(); pq.pop(); if (d != dist[u]) continue; for (auto [v, w] : g[u]) { if (dist[v] > d + w) { dist[v] = d + w; pq.push({dist[v], v}); } }}DSU / Union Find
Section titled “DSU / Union Find”struct DSU { std::vector<int> p, sz; DSU(int n) : p(n), sz(n, 1) { std::iota(p.begin(), p.end(), 0); } int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); } bool unite(int a, int b) { a = find(a); b = find(b); if (a == b) return false; if (sz[a] < sz[b]) std::swap(a, b); p[b] = a; sz[a] += sz[b]; return true; }};Segment Tree
Section titled “Segment Tree”struct SegTree { int n; std::vector<long long> t; SegTree(int n) : n(n), t(2 * n) {} void update(int i, long long v) { for (t[i += n] = v; i > 1; i >>= 1) t[i >> 1] = t[i] + t[i ^ 1]; } long long query(int l, int r) { long long ans = 0; for (l += n, r += n; l < r; l >>= 1, r >>= 1) { if (l & 1) ans += t[l++]; if (r & 1) ans += t[--r]; } return ans; }};Topological Sort
Section titled “Topological Sort”std::queue<int> q;for (int i = 0; i < n; ++i) { if (indeg[i] == 0) q.push(i);}
while (!q.empty()) { int u = q.front(); q.pop(); order.push_back(u); for (int v : g[u]) { if (--indeg[v] == 0) q.push(v); }}Priority Queue
Section titled “Priority Queue”std::priority_queue<int> maxHeap;std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;
maxHeap.push(10);minHeap.push(10);Custom Comparator
Section titled “Custom Comparator”std::sort(items.begin(), items.end(), [](const Item& a, const Item& b) { if (a.score != b.score) return a.score > b.score; return a.name < b.name;});Common Mistakes
Section titled “Common Mistakes”- Copy snippet nhưng quên include header như
<queue>,<numeric>,<algorithm>. - Không reset global state giữa nhiều test case.
- Không đổi kiểu dữ liệu sang
long longkhi cần.
Search Keywords
Section titled “Search Keywords”common snippets đoạn code mẫu fast io binary search bfs dfs dijkstra dsu union find segment tree topological sort priority queue custom comparator