Skip to content

Competitive Programming

Competitive programming ưu tiên code ngắn, đúng và dễ debug. Dùng long long cho tổng lớn. Luôn kiểm tra độ phức tạp trước khi chọn thuật toán.

using ll = long long;
const int INF = 1e9;
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::vector<long long> pref(n + 1);
for (int i = 0; i < n; ++i) {
pref[i + 1] = pref[i] + a[i];
}
long long sum = pref[r + 1] - pref[l];
int lo = 0, hi = n;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (ok(mid)) hi = mid;
else lo = mid + 1;
}
std::queue<int> q;
dist[start] = 0;
q.push(start);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : graph[u]) {
if (dist[v] == -1) {
dist[v] = dist[u] + 1;
q.push(v);
}
}
}
void dfs(int u)
{
seen[u] = true;
for (int v : graph[u]) {
if (!seen[v]) dfs(v);
}
}
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] : graph[u]) {
if (dist[v] > d + w) {
dist[v] = d + w;
pq.push({dist[v], v});
}
}
}
int find(int x)
{
return parent[x] == x ? x : parent[x] = find(parent[x]);
}
bool unite(int a, int b)
{
a = find(a);
b = find(b);
if (a == b) return false;
if (size[a] < size[b]) std::swap(a, b);
parent[b] = a;
size[a] += size[b];
return true;
}
void update(int i, int value)
{
for (tree[i += n] = value; i > 1; i >>= 1) {
tree[i >> 1] = tree[i] + tree[i ^ 1];
}
}
int query(int l, int r)
{
int ans = 0;
for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
if (l & 1) ans += tree[l++];
if (r & 1) ans += tree[--r];
}
return ans;
}
  • Dùng int cho distance Dijkstra khi trọng số/tổng đường đi lớn.
  • Binary search sai invariant giữa [lo, hi] và [lo, hi).
  • DFS recursion quá sâu gây stack overflow.

competitive programming lập trình thi đấu fast io prefix sum binary search bfs dfs dijkstra dsu union find segment tree