본문으로 건너뛰기
Previous
Next
C++ Coding Test Tips — Complete Guide

C++ Coding Test Tips — Complete Guide

C++ Coding Test Tips — Complete Guide

이 글의 핵심

C++ coding test tips - 10 secrets to pass "Baekjoon/Programmers". Explains essential templates, I/O optimization, STL container usage, algorithm patterns, time complexity checks, and common mistakes with practical code.

Essential Coding Test Template

#include <bits/stdc++.h>  // Universal header (includes most STL)
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);  // Speed up I/O
    cin.tie(NULL);
    
    // Write code here
    
    return 0;
}

Tip 1: I/O Optimization

Prevent TLE (Time Limit Exceeded)

// ❌ Slow code
cout << x << endl;  // endl flushes buffer, slow

// ✅ Fast code
cout << x << '\n';  // Use \n

Handle Large Input

// Fast input
int n;
cin >> n;
vector<int> v(n);
for (int& x : v) cin >> x;  // Use reference

Tip 2: STL Container Usage

vector (Dynamic Array)

vector<int> v;
v.push_back(1);      // Add to end
v.pop_back();        // Remove from end
v.size();            // Size
v[0];                // Access (fast)

map (Key-Value Pairs)

map<string, int> m;
m[apple] = 100;
m.count("apple");    // Exists? (0 or 1)
m.find("apple");     // Find

set (Unique Elements)

set<int> s;
s.insert(1);         // Add
s.erase(1);          // Remove
s.count(1);          // Exists?

Tip 3: Frequently Used Algorithms

Sorting

vector<int> v = {3, 1, 4, 1, 5};

// Ascending
sort(v.begin(), v.end());

// Descending
sort(v.begin(), v.end(), greater<int>());

// Custom sort
sort(v.begin(), v.end(), [](int a, int b) {
    return a > b;  // Descending
});
vector<int> v = {1, 2, 3, 4, 5};

// Find value
bool found = binary_search(v.begin(), v.end(), 3);

// Find position
auto it = lower_bound(v.begin(), v.end(), 3);
int index = it - v.begin();

Permutation/Combination

vector<int> v = {1, 2, 3};

// Next permutation
do {
    // Print v
} while (next_permutation(v.begin(), v.end()));

Tip 4: Time Complexity Check

Input SizeTime ComplexityAlgorithm
n ≤ 10O(n!)Brute force
n ≤ 20O(2^n)Bitmask
n ≤ 500O(n³)Floyd-Warshall
n ≤ 2,000O(n²)Double loop
n ≤ 100,000O(n log n)Sorting
n ≤ 1,000,000O(n)Linear search

Tip 5: Common Mistakes

Mistake 1: int Overflow

// ❌ Overflow
int a = 1000000;
int b = 1000000;
int c = a * b;  // Overflow!

// ✅ Use long long
long long c = (long long)a * b;

Mistake 2: Array Out of Bounds

// ❌ Dangerous code
int arr[100];
arr[100] = 1;  // Out of bounds!

// ✅ Use vector (safe)
vector<int> v(100);
v[99] = 1;  // OK

Mistake 3: Not Initializing

// ❌ Garbage values
int dp[100][100];
// dp[i][j] has garbage values

// ✅ Initialize
int dp[100][100] = {0};
// Or
memset(dp, 0, sizeof(dp));

Tip 6: Debugging Tips

// Debug output (remove before submission)
#define DEBUG
#ifdef DEBUG
    #define debug(x) cout << #x << " = " << x << endl
#else
    #define debug(x)
#endif

debug(n);  // Prints "n = 10"

Tip 7: Frequently Appearing Patterns

Two Pointers

int left = 0, right = 0;
while (right < n) {
    // Check condition
    if (condition) {
        // Update answer
        left++;
    }
    right++;
}

Sliding Window

int sum = 0;
for (int i = 0; i < k; i++) sum += arr[i];

for (int i = k; i < n; i++) {
    sum += arr[i] - arr[i-k];
    // Update answer
}

Tip 8: Test Room Checklist

  • I/O optimization (sync_with_stdio, cin.tie)
  • Use \n instead of endl
  • Check int overflow
  • Check array bounds
  • Verify initialization
  • Calculate time complexity
  • Test edge cases (n=0, n=1)

Tip 9: Frequently Appearing Types on Baekjoon

Type 1: Implementation (Simulation)

// Example: Array rotation, clock simulation
// Key: Understand problem precisely and implement

Representative Problems:

  • Baekjoon 14499 (Rolling Dice)
  • Baekjoon 14503 (Robot Cleaner)

Tips:

  • Check all conditions thoroughly
  • Verify intermediate states with debug output

Type 2: Greedy

// Example: Coin change, meeting room scheduling
// Key: Sort then make greedy choice

vector<pair<int,int>> meetings;
sort(meetings.begin(), meetings.end(), [](auto a, auto b) {
    return a.second < b.second;  // Sort by end time
});

Representative Problems:

  • Baekjoon 11047 (Coin 0)
  • Baekjoon 1931 (Meeting Room Assignment)

Type 3: Dynamic Programming (DP)

// Example: Fibonacci, knapsack problem
// Key: Formulate recurrence relation

int dp[1001];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
    dp[i] = dp[i-1] + dp[i-2];
}

Representative Problems:

  • Baekjoon 1003 (Fibonacci Function)
  • Baekjoon 9251 (LCS)

Type 4: Graph Traversal (BFS/DFS)

// BFS (shortest distance)
queue<int> q;
q.push(start);
visited[start] = true;

while (!q.empty()) {
    int cur = q.front();
    q.pop();
    
    for (int next : graph[cur]) {
        if (!visited[next]) {
            visited[next] = true;
            q.push(next);
        }
    }
}

Representative Problems:

  • Baekjoon 1260 (DFS and BFS)
  • Baekjoon 7576 (Tomato)

Tip 10: Frequently Used STL Functions

Max/Min

int maxVal = *max_element(v.begin(), v.end());
int minVal = *min_element(v.begin(), v.end());

Sum

int sum = accumulate(v.begin(), v.end(), 0);

Remove Duplicates

sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());

Reverse

reverse(v.begin(), v.end());

Count

int cnt = count(v.begin(), v.end(), target);

Practical Problem Examples

Example 1: Two Sum (Baekjoon Style)

Problem: Find two numbers that sum to target in array

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

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    int n, target;
    cin >> n >> target;
    
    vector<int> arr(n);
    for (int& x : arr) cin >> x;
    
    // Two pointers
    sort(arr.begin(), arr.end());
    int left = 0, right = n - 1;
    int count = 0;
    
    while (left < right) {
        int sum = arr[left] + arr[right];
        if (sum == target) {
            count++;
            left++;
            right--;
        } else if (sum < target) {
            left++;
        } else {
            right--;
        }
    }
    
    cout << count << '\n';
    return 0;
}

Example 2: Maximum Subarray Sum

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

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    
    int n;
    cin >> n;
    
    vector<int> arr(n);
    for (int& x : arr) cin >> x;
    
    // Kadane's algorithm
    int maxSum = arr[0];
    int currentSum = arr[0];
    
    for (int i = 1; i < n; i++) {
        currentSum = max(arr[i], currentSum + arr[i]);
        maxSum = max(maxSum, currentSum);
    }
    
    cout << maxSum << '\n';
    return 0;
}

Language Comparison

FeatureC++PythonJava
Speed⚡⚡⚡⚡⚡
Difficulty😰😊😐
STLPowerfulSimpleModerate
DebuggingHardEasyModerate

Recommendation:

  • Tight time limit → C++
  • Fast implementation → Python
  • Stability → Java

FAQ

Q1: What is bits/stdc++.h?

A: GCC-only universal header.

Advantages:

  • Includes all STL (iostream, vector, algorithm, etc.)
  • One line

Disadvantages:

  • Only GCC/Clang (not MSVC)
  • Slow compilation

Alternative (MSVC, etc.):

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <queue>

Q2: Is using namespace std okay?

A: Fine for coding tests.

Coding Tests:

using namespace std;  // OK (shorter code)

Production Projects:

// Not recommended (name conflicts)
using namespace std;

// Recommended
std::cout << "Hello" << std::endl;

Q3: Time limit exceeded keeps happening!

A: Check the following.

Checklist:

  1. I/O optimization (sync_with_stdio(false))
  2. Use \n instead of endl
  3. Check time complexity (O(n²) with n=100,000?)
  4. Remove unnecessary operations
  5. Use STL algorithms (optimized)

Example:

// ❌ O(n²) - TLE
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        // ...
    }
}

// ✅ O(n log n) - Pass
sort(v.begin(), v.end());

Q4: How to solve memory limit exceeded?

A: Reduce memory usage.

Checklist:

  1. Remove unnecessary arrays
  2. Minimize array size
  3. Use bitset instead of bool array
  4. Reduce recursion depth

Example:

// ❌ Memory exceeded
int arr[1000000][1000];  // 4GB!

// ✅ Allocate only needed
vector<int> arr(n);  // Only n elements

Q5: Difference between Baekjoon and Programmers?

A: I/O method differs.

Baekjoon:

  • Standard I/O (cin, cout)
  • Process directly in main function

Programmers:

  • Function implementation style
  • I/O handled automatically
// Baekjoon style
int main() {
    int n;
    cin >> n;
    cout << n << '\n';
}

// Programmers style
int solution(int n) {
    return n;
}

Q6: How long to prepare for coding tests?

A: Depends on skill level.

Beginner (with C++ basics):

  • Duration: 3-6 months
  • Daily: 2-3 problems
  • Goal: Baekjoon Silver~Gold

Intermediate (with algorithm basics):

  • Duration: 1-3 months
  • Daily: 3-5 problems
  • Goal: Baekjoon Gold~Platinum

Recommended Order:

  1. Bronze 30 problems (1 week)
  2. Silver 50 problems (1 month)
  3. Gold 30 problems (2 months)
  4. Past exam problems (1 month)

Posts connected to this topic.


Practical Tips

Tips you can apply immediately in practice.

Debugging Tips

  • Check compiler warnings first when problems occur
  • Reproduce problem with simple test cases
  • Use print debugging to trace execution

Performance Tips

  • Choose correct algorithm class for input size
  • Optimize I/O only after algorithm is correct
  • Profile before optimizing

Code Review Tips

  • Pre-check frequently pointed out parts
  • Follow team coding conventions
  • Write clear variable names

Practical Checklist

Before Solving

  • Understand problem constraints (n range, time limit)
  • Identify edge cases (empty, size 1, max size)
  • Estimate required time complexity

While Solving

  • Handle all edge cases?
  • Check for overflow?
  • Verify boundary conditions?

After Solving

  • Test with example inputs?
  • Test edge cases?
  • Check output format?

Keywords

C++, Coding Test, Baekjoon, Programmers, STL, Algorithm, Tips, I/O Optimization, Time Complexity, Two Pointers, Sliding Window, BFS, DFS, DP, Greedy


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.


이 글에서 다루는 키워드 (관련 검색어)

C++, Coding Test, Baekjoon, Programmers, STL, Algorithm, Tips 등으로 검색하시면 이 글이 도움이 됩니다.