Some C++ Contest Tricks I Wish I Were Told

  1. #include <bits/stdc++.h> is a much better option over listing the libraries you use manually, especially now that prewritten code is banned. Use it! If your compilation complains such a file does not exist, there are numerous methods out there to add this file. Just use Google.

  2. Use GCC over Clang! Clang often complains about C++ versions and spacing. If you use GCC, use policy based data structures for order statistics trees (basically sets with indices on them!) and faster hash tables! This also opens the door to the possibility of iterative sparse segment trees among many other data structures.

  3. 0/1 knapsack tricks for dynamic programming: For starters, you can space optimize the standard 0/1 knapsack with a sliding window technique. You can use the exact same code for your unbounded knapsack and 0/1 knapsack! Just loop backwards.

  4. Ever wish you could pass arrays into functions like you can vectors? Well, you can with std::arrayThis is a better alternative to tuples (and in some cases even pairs).

  5. For prefix sums, you can use partial_sum(a,a+n,b) to prefix sum the first n elements of an array a and put this result into b. To make an array its own prefix sum, you can just do partial_sum(a,a+n,a). In fact, there's also a function to create difference arrays (inverse prefix sums). You can do adjacent_difference(a,a+n,b) and adjacent_difference(a,a+n,a) respectively.

Last updated