Open In App

Some important shortcuts in Competitive Programming

Last Updated : 25 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

One of the best ways to save time in competitive programming is by creating snippets. Snippets are reusable pieces of code that can be used easily for program creation or repeated tasks. It not only eases the efforts put into writing any code but also saves time for debugging as you know that is stored from the very begging. In this article, we will discuss all the components of snippets and some other tricks.

The most common tools to save time in C/C++ are typedefs and macros. Unfortunately, these features are not available in many other languages like Java. Here are some examples of our C/C++ code Shortcuts:

// Shortcuts for "common" data types in contests
typedef long long ll; 
typedef pair<int, int> ii; 
typedef vector<ii> vii;
typedef vector<int> vi;
// you can also use "#define" instead of "typedef"

Infinite:

const int INF = 0x3f3f3f3f;

Modulus:

const int mod = 1000000007;

Setting up values in an array:

// initialize DP memoization table with -1
memset(memo, -1, sizeof memo); 

// to clear array of integers
memset(arr, 0, sizeof arr); 

// Use a vector to creates a dynamic array 
// and initialize it in one statement.
// Creates a vector of size N and values as 0.
vector<int> v(N, 0); // OR vi v(N, 0); 

The following shortcuts can save time in almost all languages including Java:

// to simplify: if (a) ans = b; else ans = c;
ans = a ? b : c; 

// to simplify: ans = ans + val; and its variants
ans += val; 

// index++; if (index >= n) index = 0;
index = (index + 1) % n; 

// index--; if (index < 0) index = n - 1;
index = (index + n - 1) % n; 

// for rounding to nearest integer
int ans = (int)((double)d + 0.5); 

// min/max shortcut to update max/min
ans = min(ans, new_computation); 
ans = max(ans, new_computation); 

// max/min shortcut for more than two numbers
ans = max(a, max(b,c));
ans = min(a, min(b,c));

// To return true if a value matches a given
// number, else return false
// if (val == given_no) return true; 
// else return false;
return (val == given_no)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads