Competitive Programming with C++

Master algorithms and data structures for coding contests

šŸ† Competitive Programming with C++

Excel in coding competitions with optimized algorithms, efficient data structures, and fast I/O techniques. Learn problem-solving strategies used in contests like Codeforces, AtCoder, and ICPC with time-tested competitive programming templates.


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

#define fast_io ios_base::sync_with_stdio(false); cin.tie(NULL);
#define ll long long
#define vi vector<int>
#define pb push_back

int main() {
    fast_io
    // Your competitive programming solution here
    return 0;
}
                                    

Competitive Programming Topics

⚔

Fast I/O & Templates

Speed optimization techniques

Fast I/O Macros Templates
šŸ”

Search & Sort

Fundamental algorithms

Binary Search Quick Sort Merge Sort
šŸ“Š

Data Structures

Contest-ready structures

Segment Tree Fenwick Tree Disjoint Set
🌐

Graph Algorithms

Network problem solving

DFS/BFS Dijkstra MST

šŸ”¹ Competitive Programming Template

Standard template for fast contest coding:

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

// Type definitions
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

// Macros
#define fast_io ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(), (x).end()
#define sz(x) (int)(x).size()
#define F first
#define S second

// Constants
const int MOD = 1e9 + 7;
const int INF = 1e9;
const ll LINF = 1e18;

// Utility functions
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }
ll power(ll a, ll b, ll mod = MOD) {
    ll res = 1;
    while (b > 0) {
        if (b & 1) res = (res * a) % mod;
        a = (a * a) % mod;
        b >>= 1;
    }
    return res;
}

void solve() {
    int n;
    cin >> n;
    
    vi arr(n);
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    
    // Your solution logic here
    
    cout << "Answer" << "\n";
}

int main() {
    fast_io
    
    int t = 1;
    cin >> t;  // Remove this line if single test case
    
    while (t--) {
        solve();
    }
    
    return 0;
}

šŸ”¹ Binary Search Implementation

Efficient searching with binary search variations:

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

// Standard binary search
int binarySearch(vector<int>& arr, int target) {
    int left = 0, right = arr.size() - 1;
    
    while (left <= right) {
        int mid = left + (right - left) / 2;
        
        if (arr[mid] == target) {
            return mid;
        } else if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    
    return -1; // Not found
}

// Lower bound: first element >= target
int lowerBound(vector<int>& arr, int target) {
    int left = 0, right = arr.size();
    
    while (left < right) {
        int mid = left + (right - left) / 2;
        
        if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    
    return left;
}

// Upper bound: first element > target
int upperBound(vector<int>& arr, int target) {
    int left = 0, right = arr.size();
    
    while (left < right) {
        int mid = left + (right - left) / 2;
        
        if (arr[mid] <= target) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    
    return left;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    vector<int> arr = {1, 2, 2, 2, 3, 4, 5};
    int target = 2;
    
    cout << "Array: ";
    for (int x : arr) cout << x << " ";
    cout << "\n";
    
    cout << "Binary search for " << target << ": " << binarySearch(arr, target) << "\n";
    cout << "Lower bound of " << target << ": " << lowerBound(arr, target) << "\n";
    cout << "Upper bound of " << target << ": " << upperBound(arr, target) << "\n";
    
    return 0;
}

Sample Output:

Array: 1 2 2 2 3 4 5
Binary search for 2: 1
Lower bound of 2: 1
Upper bound of 2: 4

šŸ”¹ Graph Traversal (DFS & BFS)

Essential graph algorithms for competitive programming:

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

class Graph {
private:
    int vertices;
    vector<vector<int>> adjList;
    
public:
    Graph(int v) : vertices(v) {
        adjList.resize(v);
    }
    
    void addEdge(int u, int v) {
        adjList[u].push_back(v);
        adjList[v].push_back(u); // For undirected graph
    }
    
    void DFS(int start) {
        vector<bool> visited(vertices, false);
        stack<int> st;
        
        st.push(start);
        cout << "DFS traversal: ";
        
        while (!st.empty()) {
            int current = st.top();
            st.pop();
            
            if (!visited[current]) {
                visited[current] = true;
                cout << current << " ";
                
                // Add neighbors to stack (in reverse order for correct traversal)
                for (int i = adjList[current].size() - 1; i >= 0; i--) {
                    if (!visited[adjList[current][i]]) {
                        st.push(adjList[current][i]);
                    }
                }
            }
        }
        cout << "\n";
    }
    
    void BFS(int start) {
        vector<bool> visited(vertices, false);
        queue<int> q;
        
        visited[start] = true;
        q.push(start);
        cout << "BFS traversal: ";
        
        while (!q.empty()) {
            int current = q.front();
            q.pop();
            cout << current << " ";
            
            for (int neighbor : adjList[current]) {
                if (!visited[neighbor]) {
                    visited[neighbor] = true;
                    q.push(neighbor);
                }
            }
        }
        cout << "\n";
    }
    
    // Check if graph is connected
    bool isConnected() {
        vector<bool> visited(vertices, false);
        queue<int> q;
        
        visited[0] = true;
        q.push(0);
        int count = 1;
        
        while (!q.empty()) {
            int current = q.front();
            q.pop();
            
            for (int neighbor : adjList[current]) {
                if (!visited[neighbor]) {
                    visited[neighbor] = true;
                    q.push(neighbor);
                    count++;
                }
            }
        }
        
        return count == vertices;
    }
};

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    Graph g(6);
    
    // Add edges
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 3);
    g.addEdge(1, 4);
    g.addEdge(2, 5);
    
    g.DFS(0);
    g.BFS(0);
    
    cout << "Is connected: " << (g.isConnected() ? "Yes" : "No") << "\n";
    
    return 0;
}

šŸ”¹ Dynamic Programming Template

Common DP patterns for contest problems:

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

// 1. Fibonacci with memoization
map<int, long long> memo;
long long fibonacci(int n) {
    if (n <= 1) return n;
    if (memo.find(n) != memo.end()) return memo[n];
    
    return memo[n] = fibonacci(n-1) + fibonacci(n-2);
}

// 2. Coin Change Problem
int coinChange(vector<int>& coins, int amount) {
    vector<int> dp(amount + 1, amount + 1);
    dp[0] = 0;
    
    for (int i = 1; i <= amount; i++) {
        for (int coin : coins) {
            if (i - coin >= 0) {
                dp[i] = min(dp[i], dp[i - coin] + 1);
            }
        }
    }
    
    return dp[amount] > amount ? -1 : dp[amount];
}

// 3. Longest Common Subsequence
int LCS(string text1, string text2) {
    int m = text1.length(), n = text2.length();
    vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
    
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (text1[i-1] == text2[j-1]) {
                dp[i][j] = dp[i-1][j-1] + 1;
            } else {
                dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
            }
        }
    }
    
    return dp[m][n];
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    // Test Fibonacci
    cout << "Fibonacci(10): " << fibonacci(10) << "\n";
    
    // Test Coin Change
    vector<int> coins = {1, 3, 4};
    cout << "Coin change for 6: " << coinChange(coins, 6) << "\n";
    
    // Test LCS
    string s1 = "abcde", s2 = "ace";
    cout << "LCS of '" << s1 << "' and '" << s2 << "': " << LCS(s1, s2) << "\n";
    
    return 0;
}

🧠 Test Your Knowledge

What is the time complexity of binary search?