Hello Codeforces!
I often see beginners struggling with writing efficient C++ code in contests. Since time is short during competitions, knowing some handy C++ tips and tricks can save you from both Time Limit Exceeded (TLE) and bugs. Here are a few that I find most useful:
1. Fast Input / Output Instead of using cin/cout with sync, always do this: ~~~~~ ios::sync_with_stdio(false); cin.tie(nullptr); ~~~~~ This makes I/O much faster (almost as good as scanf/printf).
2. Using long long Safely
In contests, integer overflow is a common bug. Always define:
using ll = long long;
And whenever you multiply large numbers, cast them: ll result = 1LL * a * b;
3. vector vs array
->vector is flexible (dynamic size). ->array<int, N> is faster for fixed sizes.
vector<int> v(n, 0); // size n, filled with 0
**4. The Power of __gcd and std::lcm**
Instead of writing your own gcd:
#include <numeric>
int g = gcd(a, b); // since C++17
int l = lcm(a, b);
5. Sorting and Custom Comparators
Need descending order? No need to write a custom comparator: sort(v.rbegin(), v.rend());
6. Prefix Sum and Partial Sum
Prefix sums are lifesavers:
vector<int> pref(n+1, 0);
for (int i = 0; i < n; i++) pref[i+1] = pref[i] + v[i];
7. Modular Arithmetic
When problems involve large numbers:
const int MOD = 1e9+7;
auto add = [&](int a, int b){ return (a + b) % MOD; };
Avoid overflow by using 1LL * a * b % MOD.
8. Useful Shortcuts
->memset(dp, -1, sizeof(dp)); → quick initialization. ->iota(v.begin(), v.end(), 0); → fill with 0,1,2,... ->lower_bound / upper_bound → binary search in O(log n).







