0% found this document useful (0 votes)
40 views14 pages

Cheat Sheet

The document discusses various data structures and algorithms. It provides code snippets and explanations for implementing common data structures like arrays, vectors, stacks and queues. It also describes algorithms for sorting, searching, prime factorization, calculating LCM and GCD.

Uploaded by

Qing Hong Boon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views14 pages

Cheat Sheet

The document discusses various data structures and algorithms. It provides code snippets and explanations for implementing common data structures like arrays, vectors, stacks and queues. It also describes algorithms for sorting, searching, prime factorization, calculating LCM and GCD.

Uploaded by

Qing Hong Boon
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Cheat Sheet

Go Green!

Data Structures
#include <bits/stdc++.h>
using II = long long int;
using III = unsigned long long int;
using namespace std;
#define MP make_pair
#define PB push_back
#define IN insert
#define P push
#define F first
#define S second
#define E erase
#define BG begin()
#define ED end()
#define SZ size()
#define NORM (200005)
#define MAXN INT32_MAX
#define T ::iterator
#define LOOP(i, n) for (II i = 0; i < n; i ++)
#define LOOP1(i, n) for (II i = 1; i <= n; i ++)

Data Structures
- Tuple
- Array
- Vector
- Set
- Multiset
- Unordered Set
- Pair
- Queue
- Priority Queue
- Map
- Multimap
- Unordered Map
- Stack

Tuple

1
tuple<char, int, float> t
t = make_tuple(’c’, 34, 2.3);

Change values of tuple


get<0>(t) = ’d’;

Get the (i-1)th element in the tuple


cout << get<i>(t) << endl;

Vector

Set

Arrange in non-increasing order


set<int, greater<int> > s1;
set<int, greater<int> >::iterator itr;
for (itr = s1.begin(); itr != s1.end(); itr) {cout << *itr << " ";}

Check if element same as previous PB’s element


cin >> ai;
LOOP (i->n)
s.insert(ai);
Temp;
If (s.size() != temp) {//}
Empty(): same as Map
Find():
auto pos = s.find(element);
// print element if it is present in set
if(pos != s.end()) cout << "Element found at position : "<< *pos;
Count():same as Map

Multiset

Arrange in non-increasing order


multiset<int, greater<int> > gquiz1;
Find () : same as Map
Count() : same as Map
Erase() : same as Map

Priority Queue

2
Map

map<key, value> m;
m.insert({key, value});
m.count();
m.find();

Sort By Value
bool sortByVal(const pair<string, int> &a, const pair<string, int> &b) {
return (a.second < b.second);
}

count()
// checks if key 1 is present or not
if (mp.count(1)) cout << "The key 1 is present\n";

find()
// find() function finds the position at which 3 is present
for (auto itr = mp.find(3); itr != mp.end(); itr)
cout << itr->first << ’\t’ << itr->second << ’\n’;

Sort in Map
bool cmp(pair<string, int>& a, pair<string, int>& b)
return a.second < b.second;

void sort(map<string, int>& M){


vector<pair<string, int> > A;
for (auto& it : M) { A.push_back(it); }
sort(A.begin(), A.end(), cmp);

for (auto& it : A) {
cout << it.first << ’ ’ << it.second << endl;
}
}
int main(){
map<string, int> M;
M = { { "GfG", 3 },{ "To", 2 },{ "Welcome", 1 } };
sort(M);
}

Decimal Places

3
cout << showpoint << fixed << setprecision() << "String" << endl;

Algorithms
Finding min/max element(s)’s index
int index = max_element(a.begin(), a.end());

4
To erase element

a.erase(a.begin(), index);

Check if array is non-decreasing

bool ok = true;
for (int ...){
ok = ok & (a[i] <= a[i + 1])
}
if (ok == true){
cout << "YES";
}
else cout << "NO";

Checking if a number is prime

bool isPrime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;

return true;
}

5
Convert a number from base a to base b

// Function to return ASCII value of a character


int val(char c)
{
if (c >= ’0’ && c <= ’9’)
return (int)c - ’0’;
else
return (int)c - ’A’ + 10;
}

// Function to convert a number from given base to decimal number


int toDeci(string str, int base)
{
// Stores the length of the string
int len = str.size();

// Initialize power of base


int power = 1;

// Initialize result
int num = 0;

// Decimal equivalent is str[len-1]*1 +


// str[len-2]*base + str[len-3]*(base^2) + ...
for (int i = len - 1; i >= 0; i--) {

// A digit in input number must be less than number’s base


if (val(str[i]) >= base) {
printf("Invalid Number");
return -1;
}

// Update num
num += val(str[i]) * power;

// Update power
power = power * base;
}

return num;
}

6
// Function to return equivalent character of a given value
char reVal(int num)
{
if (num >= 0 && num <= 9)
return (char)(num + ’0’);
else
return (char)(num - 10 + ’A’);
}

// Function to convert a given decimal number to a given base


string fromDeci(int base, int inputNum)
{
// Store the result
string res = "";

// Repeatedly divide inputNum by base and take remainder


while (inputNum > 0) {

// Update res
res += reVal(inputNum % base);

// Update inputNum
inputNum /= base;
}

// Reverse the result


reverse(res.begin(), res.end());

return res;
}

// Function to convert a given number from a base to another base

7
void convertBase(string s, int a, int b)
{
// Convert the number from base A to decimal
int num = toDeci(s, a);

// Convert the number from decimal to base B


string ans = fromDeci(b, num);

// Print the result


cout << ans;
}

LCM of two numbers

long long gcd(long long int a, long long int b)


{
if (b == 0)
return a;
return gcd(b, a % b);
}

// Function to return LCM of two numbers


long long lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}

Full implementation of sqrt() function (included in <math.h>)

8
int sqrt(int x){
if (x == 0 || x == 1) return x;
int start = 1, end = x/2, ans;
while (start <= end) {
int mid = (start + end) / 2;
int sqr = mid * mid;
if (sqr == x) return mid;

if(mid*mid <= x){


start = mid+1;
ans = mid;
}

if (sqr <= x){


start = mid + 1;
ans = mid;
}else end = mid - 1;
}
return ans;
}

Finding L.C.M. of an array of numbers

// Utility function to find GCD of ’a’ and ’b’


int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}

// Returns LCM of array elements


ll findlcm(int arr[], int n)
{
// Initialize result
ll ans = arr[0];

// ans contains LCM of arr[0], ..arr[i] after i’th iteration,


for (int i = 1; i < n; i++)
ans = (((arr[i] * ans)) /
(gcd(arr[i], ans)));

return ans;
}

9
Finding G.C.D. of an array of numbers

int gcd(int a, int b)


{
if (a == 0)
return b;
return gcd(b % a, a);
}

// Function to find gcd of array of numbers


int findGCD(int arr[], int n)
{
int result = arr[0];
for (int i = 1; i < n; i++)
{
result = gcd(arr[i], result);

if(result == 1)
{
return 1;
}
}
return result;
}

High Occurrence Rate:


- vector <vector <pair <int, int>> x
- map <pair<int, int> , int> x
- map <pair<int, int> , pair<int,int>> x
- map <pair<int, int>, vector> x
- multiset <map <int, int>> x
- multiset <vector<int>> x
- unordered_set <pair<int, int> x

10
void find_prime(int n, bool prime[], bool primesquare[], int a[])
{

for (int i = 2; i <= n; i++) prime[i] = true;


for (int i = 0; i <= (n * n + 1); i++) primesquare[i] = false;

prime[1] = false;

for (int p = 2; p * p <= n; p++) {


if (prime[p] == true) {
for (int i = p * p; i <= n; i += p) prime[i] = false;
}
}

int j = 0;
for (int p = 2; p <= n; p++) {
if (prime[p]) {
a[j] = p;
primesquare[p * p] = true;
j++;
}
}
}

int countDivisors(int n)
{
if (n == 1) return 1;

bool prime[n + 1], primesquare[n * n + 1];


int a[n];

find_prime(n, prime, primesquare, a);

int ans = 1;
for (int i = 0;; i++) {
if (a[i] * a[i] * a[i] > n) break;
int cnt = 1;
while (n % a[i] == 0){
n = n / a[i];
cnt = cnt + 1;
}
ans = ans * cnt;
}
if (prime[n]) ans = ans * 2;
else if (primesquare[n]) ans = ans * 3;
else if (n != 1) ans = ans * 4;
return ans;
} 11
Finding Number of Perfect Powers

// Function that keeps all the odd power


// numbers upto n
int powerNumbers(int n)
{
// v is going to store all power numbers
vector<int> v;
v.push_back(1);

// Traverse through all base numbers and


// compute all their powers smaller than
// or equal to n.
for (ll i = 2; i * i <= n; i++) {
ll j = i * i;
v.push_back(j);
while (j * i <= n) {
v.push_back(j * i);
j = j * i;
}
}

// Remove all duplicates


sort(v.begin(), v.end());
v.erase(unique(v.begin(), v.end()), v.end());

return v.size();
}

Finding Determinant

12
// Dimension of input square matrix
#define N 4
// Function to get determinant of matrix
int determinantOfMatrix(int mat[N][N], int n)
{
int num1, num2, det = 1, index,
total = 1; // Initialize result

// temporary array for storing row


int temp[n + 1];

// loop for traversing the diagonal elements


for (int i = 0; i < n; i++)
{
index = i; // initialize the index

// finding the index which has non zero value


while (index < n && mat[index][i] == 0)
{
index++;
}
if (index == n) // if there is non zero element
{
// the determinant of matrix as zero
continue;
}
if (index != i)
{
// loop for swapping the diagonal element row and
// index row
for (int j = 0; j < n; j++)
{
swap(mat[index][j], mat[i][j]);
}
// determinant sign changes when we shift rows
// go through determinant properties
det = det * pow(-1, index - i);
}

// storing the values of diagonal row elements


for (int j = 0; j < n; j++)
{
temp[j] = mat[i][j];
}

13
// traversing every row below the diagonal element
for (int j = i + 1; j < n; j++)
{
num1 = temp[i]; // value of diagonal element
num2 = mat[j][i]; // value of next row element

// traversing every column of row


// and multiplying to every row
for (int k = 0; k < n; k++)
{
// multiplying to make the diagonal
// element and next row element equal
mat[j][k]
= (num1 * mat[j][k]) - (num2 * temp[k]);
}
total = total * num1; // Det(kA)=kDet(A);
}
}

// multiplying the diagonal elements to get determinant


for (int i = 0; i < n; i++)
{
det = det * mat[i][i];
}
return (det / total); // Det(kA)/k=Det(A);
}

14

You might also like