Competitive Programmer s Handbook
Basics
Key Types
Basic Types
long long - always 64 bits long double - 80 bits
Compare floats with:
if (abs(a - b) < 1e-9) {
Tricks
typedef long long ll
Math
sum(i..n) = n(n+1) / 2
sum(i)
Time Complexity
- O(2n) means you iterate through each subarray of an array of size n
- O(n!) means you iterate through all permutations of an array of size n
Data Structures
= "abde";
string s << s.substr(1, 2); // substring from index 1 with length 2 cout
Sets
;
set s.insert(5);
s.erase(5);
set
<10> s; // bitset with 10 elements
bitset
<10> s(string("01100101")); bitset
Maps
// uses a balanced binary tree. Access take O(log n)
<string, int> m;
map
// uses hashing. O(1) access
<string, int> m; unordered_map
Using Iterators
(v.begin(), v.end());
reverse
for (auto it = s.begin(); it != s.end(); it++) {
<< *it << "\n";
cout }
if (s.find(el) != s.end()); // ...
auto it = s.find(el);
<< *it << "\n"; cout
Deque
<int> d;
deque.push_back(5);
d.pop_back(); d
Priority Queues
<int, vector<int>, greater<int>> q; priority_queue
Brute Force - Complete Search
void search(int k) {
if (k == n) {
// process subset
} else {
(k + 1);
search.push_back(k);
subset(k + 1);
search.pop_back();
subset}
}
Backtracking
Begin with an empty solution and extend it step-by-step with possible solutions
- This is for when you want all possible solutions