C++ Coding Test Tips | 10 Secrets to Pass "Baekjoon/Programmers"
이 글의 핵심
C++ coding test tips summarized. #include <bits/stdc++.h>
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
});
Binary Search
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 Size | Time Complexity | Algorithm |
|---|---|---|
| n ≤ 10 | O(n!) | Brute force |
| n ≤ 20 | O(2^n) | Bitmask |
| n ≤ 500 | O(n³) | Floyd-Warshall |
| n ≤ 2,000 | O(n²) | Double loop |
| n ≤ 100,000 | O(n log n) | Sorting |
| n ≤ 1,000,000 | O(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
| Feature | C++ | Python | Java |
|---|---|---|---|
| Speed | ⚡⚡⚡ | ⚡ | ⚡⚡ |
| Difficulty | 😰 | 😊 | 😐 |
| STL | Powerful | Simple | Moderate |
| Debugging | Hard | Easy | Moderate |
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:
- I/O optimization (
sync_with_stdio(false)) - Use
\ninstead ofendl - Check time complexity (O(n²) with n=100,000?)
- Remove unnecessary operations
- 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:
- Remove unnecessary arrays
- Minimize array size
- Use bitset instead of bool array
- 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:
- Bronze 30 problems (1 week)
- Silver 50 problems (1 month)
- Gold 30 problems (2 months)
- Past exam problems (1 month)
Related Posts
Posts connected to this topic.
- C++ Coding Test | “Baekjoon·Programmers” STL Usage by Algorithm Type
- C++ Coding Test I/O | “Got TLE” sync_with_stdio Copy-Paste Template
- C++ Algorithm | “Coding Test” 10 Essential Problems
- C++ Baekjoon/Programmers Setup and I/O Optimization All-in-One [#32-1]
- Array and List | Essential Data Structures for Coding Tests Complete Guide
- C++ Algorithm Copy
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