0% found this document useful (0 votes)
9 views13 pages

Template CPP

Uploaded by

aimantahmid100
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)
9 views13 pages

Template CPP

Uploaded by

aimantahmid100
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/ 13

6/15/25, 1:12 AM template.

cpp

------------------------------------------------------------------------------------------
---------------------------------------DSU------------------------------------------------
------------------------------------------------------------------------------------------
class dsu {
public:
vector<int> p;
int n;

dsu(int _n) : n(_n) {


p.resize(n);
iota(p.begin(), p.end(), 0);
}

inline int get(int x) {


return (x == p[x] ? x : (p[x] = get(p[x])));
}

inline bool unite(int x, int y) {


x = get(x);
y = get(y);
if (x != y) {
p[x] = y;
return true;
}
return false;
}
};

------------------------------------------------------------------------------------------
-----------------------------------Hashmap------------------------------------------------
------------------------------------------------------------------------------------------
// #include<bits/extc++.h>
#include <ext/pb_ds/assoc_container.hpp>

struct splitmix64_hash {
static uint64_t splitmix64(uint64_t x) {
// http://xorshift.di.unimi.it/splitmix64.c
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}

size_t operator()(uint64_t x) const {


static const uint64_t FIXED_RANDOM = std::chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
file:///C:/Users/moazz/Desktop/template.cpp 1/13
6/15/25, 1:12 AM template.cpp
}
};

template <typename K, typename V, typename Hash = splitmix64_hash>


using HashMap = __gnu_pbds::gp_hash_table<K, V, Hash>;

template <typename K, typename Hash = splitmix64_hash>


using HashSet = HashMap<K, __gnu_pbds::null_type, Hash>;

------------------------------------------------------------------------------------------
-------------------------------Segment Tree-----------------------------------------------
------------------------------------------------------------------------------------------
class segtree {
public:
struct node {
// don't forget to set default value (used for leaves)
// not necessarily neutral element!
... a = ...;

void apply(int l, int r, ... v) {


...
}
};

node unite(const node &a, const node &b) const {


node res;
...
return res;
}

inline void push(int x, int l, int r) {


int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
// push from x into (x + 1) and z
...
/*
if (tree[x].add != 0) {
tree[x + 1].apply(l, y, tree[x].add);
tree[z].apply(y + 1, r, tree[x].add);
tree[x].add = 0;
}
*/
}

inline void pull(int x, int z) {


tree[x] = unite(tree[x + 1], tree[z]);
}

file:///C:/Users/moazz/Desktop/template.cpp 2/13
6/15/25, 1:12 AM template.cpp

int n;
vector<node> tree;

void build(int x, int l, int r) {


if (l == r) {
return;
}
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
build(x + 1, l, y);
build(z, y + 1, r);
pull(x, z);
}

template <typename M>


void build(int x, int l, int r, const vector<M> &v) {
if (l == r) {
tree[x].apply(l, r, v[l]);
return;
}
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
build(x + 1, l, y, v);
build(z, y + 1, r, v);
pull(x, z);
}

node get(int x, int l, int r, int ll, int rr) {


if (ll <= l && r <= rr) {
return tree[x];
}
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
push(x, l, r);
node res{};
if (rr <= y) {
res = get(x + 1, l, y, ll, rr);
} else {
if (ll > y) {
res = get(z, y + 1, r, ll, rr);
} else {
res = unite(get(x + 1, l, y, ll, rr), get(z, y + 1, r, ll, rr));
}
}
pull(x, z);
return res;

file:///C:/Users/moazz/Desktop/template.cpp 3/13
6/15/25, 1:12 AM template.cpp
}

template <typename... M>


void modify(int x, int l, int r, int ll, int rr, const M&... v) {
if (ll <= l && r <= rr) {
tree[x].apply(l, r, v...);
return;
}
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
push(x, l, r);
if (ll <= y) {
modify(x + 1, l, y, ll, rr, v...);
}
if (rr > y) {
modify(z, y + 1, r, ll, rr, v...);
}
pull(x, z);
}

int find_first_knowingly(int x, int l, int r, const function<bool(const node&)> &f) {


if (l == r) {
return l;
}
push(x, l, r);
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
int res;
if (f(tree[x + 1])) {
res = find_first_knowingly(x + 1, l, y, f);
} else {
res = find_first_knowingly(z, y + 1, r, f);
}
pull(x, z);
return res;
}

int find_first(int x, int l, int r, int ll, int rr, const function<bool(const node&)> &f) {
if (ll <= l && r <= rr) {
if (!f(tree[x])) {
return -1;
}
return find_first_knowingly(x, l, r, f);
}
push(x, l, r);
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);

file:///C:/Users/moazz/Desktop/template.cpp 4/13
6/15/25, 1:12 AM template.cpp
int res = -1;
if (ll <= y) {
res = find_first(x + 1, l, y, ll, rr, f);
}
if (rr > y && res == -1) {
res = find_first(z, y + 1, r, ll, rr, f);
}
pull(x, z);
return res;
}

int find_last_knowingly(int x, int l, int r, const function<bool(const node&)> &f) {


if (l == r) {
return l;
}
push(x, l, r);
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
int res;
if (f(tree[z])) {
res = find_last_knowingly(z, y + 1, r, f);
} else {
res = find_last_knowingly(x + 1, l, y, f);
}
pull(x, z);
return res;
}

int find_last(int x, int l, int r, int ll, int rr, const function<bool(const node&)> &f) {
if (ll <= l && r <= rr) {
if (!f(tree[x])) {
return -1;
}
return find_last_knowingly(x, l, r, f);
}
push(x, l, r);
int y = (l + r) >> 1;
int z = x + ((y - l + 1) << 1);
int res = -1;
if (rr > y) {
res = find_last(z, y + 1, r, ll, rr, f);
}
if (ll <= y && res == -1) {
res = find_last(x + 1, l, y, ll, rr, f);
}
pull(x, z);
return res;

file:///C:/Users/moazz/Desktop/template.cpp 5/13
6/15/25, 1:12 AM template.cpp
}

segtree(int _n) : n(_n) {


assert(n > 0);
tree.resize(2 * n - 1);
build(0, 0, n - 1);
}

template <typename M>


segtree(const vector<M> &v) {
n = v.size();
assert(n > 0);
tree.resize(2 * n - 1);
build(0, 0, n - 1, v);
}

node get(int ll, int rr) {


assert(0 <= ll && ll <= rr && rr <= n - 1);
return get(0, 0, n - 1, ll, rr);
}

node get(int p) {
assert(0 <= p && p <= n - 1);
return get(0, 0, n - 1, p, p);
}

template <typename... M>


void modify(int ll, int rr, const M&... v) {
assert(0 <= ll && ll <= rr && rr <= n - 1);
modify(0, 0, n - 1, ll, rr, v...);
}

// find_first and find_last call all FALSE elements


// to the left (right) of the sought position exactly once

int find_first(int ll, int rr, const function<bool(const node&)> &f) {


assert(0 <= ll && ll <= rr && rr <= n - 1);
return find_first(0, 0, n - 1, ll, rr, f);
}

int find_last(int ll, int rr, const function<bool(const node&)> &f) {


assert(0 <= ll && ll <= rr && rr <= n - 1);
return find_last(0, 0, n - 1, ll, rr, f);
}
};

file:///C:/Users/moazz/Desktop/template.cpp 6/13
6/15/25, 1:12 AM template.cpp
------------------------------------------------------------------------------------------
-----------------------------------Dijkstra-----------------------------------------------
------------------------------------------------------------------------------------------

template <typename T>


vector<T> dijkstra(const graph<T> &g, int start) {
assert(0 <= start && start < g.n);
vector<T> dist(g.n, numeric_limits<T>::max());
priority_queue<pair<T, int>, vector<pair<T, int>>, greater<>> s;
dist[start] = 0;
s.emplace(dist[start], start);
while (!s.empty()) {
auto [expected, i] = s.top();
s.pop();
if (dist[i] != expected) {
continue;
}
for (int id : g.g[i]) {
auto &e = g.edges[id];
int to = e.from ^ e.to ^ i;
if (dist[i] + e.cost < dist[to]) {
dist[to] = dist[i] + e.cost;
s.emplace(dist[to], to);
}
}
}
return dist;
// returns numeric_limits<T>::max() if there's no path
}

------------------------------------------------------------------------------------------
-----------------------------------Graph--------------------------------------------------
------------------------------------------------------------------------------------------

template <typename T>


class graph {
public:
struct edge {
int from;
int to;
T cost;
};

vector<edge> edges;
vector<vector<int>> g;
int n;

file:///C:/Users/moazz/Desktop/template.cpp 7/13
6/15/25, 1:12 AM template.cpp
graph(int _n) : n(_n) {
g.resize(n);
}

virtual int add(int from, int to, T cost) = 0;


};

------------------------------------------------------------------------------------------
-----------------------------------Suffix Array-------------------------------------------
------------------------------------------------------------------------------------------

template <typename T>


vector<int> suffix_array(int n, const T &s, int char_bound) {
vector<int> a(n);
if (n == 0) {
return a;
}
if (char_bound != -1) {
vector<int> aux(char_bound, 0);
for (int i = 0; i < n; i++) {
aux[s[i]]++;
}
int sum = 0;
for (int i = 0; i < char_bound; i++) {
int add = aux[i];
aux[i] = sum;
sum += add;
}
for (int i = 0; i < n; i++) {
a[aux[s[i]]++] = i;
}
} else {
iota(a.begin(), a.end(), 0);
sort(a.begin(), a.end(), [&s](int i, int j) { return s[i] < s[j]; });
}
vector<int> sorted_by_second(n);
vector<int> ptr_group(n);
vector<int> new_group(n);
vector<int> group(n);
group[a[0]] = 0;
for (int i = 1; i < n; i++) {
group[a[i]] = group[a[i - 1]] + (!(s[a[i]] == s[a[i - 1]]));
}
int cnt = group[a[n - 1]] + 1;
int step = 1;
while (cnt < n) {

file:///C:/Users/moazz/Desktop/template.cpp 8/13
6/15/25, 1:12 AM template.cpp
int at = 0;
for (int i = n - step; i < n; i++) {
sorted_by_second[at++] = i;
}
for (int i = 0; i < n; i++) {
if (a[i] - step >= 0) {
sorted_by_second[at++] = a[i] - step;
}
}
for (int i = n - 1; i >= 0; i--) {
ptr_group[group[a[i]]] = i;
}
for (int i = 0; i < n; i++) {
int x = sorted_by_second[i];
a[ptr_group[group[x]]++] = x;
}
new_group[a[0]] = 0;
for (int i = 1; i < n; i++) {
if (group[a[i]] != group[a[i - 1]]) {
new_group[a[i]] = new_group[a[i - 1]] + 1;
} else {
int pre = (a[i - 1] + step >= n ? -1 : group[a[i - 1] + step]);
int cur = (a[i] + step >= n ? -1 : group[a[i] + step]);
new_group[a[i]] = new_group[a[i - 1]] + (pre != cur);
}
}
swap(group, new_group);
cnt = group[a[n - 1]] + 1;
step <<= 1;
}
return a;
}

template <typename T>


vector<int> suffix_array(const T &s, int char_bound) {
return suffix_array((int) s.size(), s, char_bound);
}

template <typename T>


vector<int> build_lcp(int n, const T &s, const vector<int> &sa) {
assert((int) sa.size() == n);
vector<int> pos(n);
for (int i = 0; i < n; i++) {
pos[sa[i]] = i;
}
vector<int> lcp(max(n - 1, 0));
int k = 0;

file:///C:/Users/moazz/Desktop/template.cpp 9/13
6/15/25, 1:12 AM template.cpp
for (int i = 0; i < n; i++) {
k = max(k - 1, 0);
if (pos[i] == n - 1) {
k = 0;
} else {
int j = sa[pos[i] + 1];
while (i + k < n && j + k < n && s[i + k] == s[j + k]) {
k++;
}
lcp[pos[i]] = k;
}
}
return lcp;
}

template <typename T>


vector<int> build_lcp(const T &s, const vector<int> &sa) {
return build_lcp((int) s.size(), s, sa);
}

------------------------------------------------------------------------------------------
-----------------------------------DFS----------------------------------------------------
------------------------------------------------------------------------------------------

#include "../c++_template.cpp"

// =========================
// Depth First Search (DFS)
// =========================
const int MAXN = 1000;
vector<int> g[MAXN];
bool visited[MAXN];
int n;

//recursive
void dfs(int u) {
visited[u] = true;
for(int v : g[u]) {
if(!visited[v]) {
dfs(v);
}
}
}

file:///C:/Users/moazz/Desktop/template.cpp 10/13
6/15/25, 1:12 AM template.cpp
//recursive, using depth
int depth[MAXN];
void dfs(int u, int d) {
depth[u] = d;
for(int v : g[u]) {
if(depth[v] == -1) { // not visited yet
dfs(v, d+1);
}
}
}

//iterative
void dfs(int root) {
stack<int> s;
s.push(root);
visited[root] = true;
while (!s.empty()) {
int u = s.top(); s.pop();
for (int v : g[u]) {
if (!visited[v]) {
visited[u] = true;
s.push(v);
}
}
}
}

//-----------------------------
// Finding connected components
//-----------------------------
int count_cc() {
int count = 0;
memset(visited, 0, sizeof(bool)*n);
rep(i,0,n) {
if (!visited[i]) {
count++, dfs(i);
}
}
return count;
}

//------------------------------
// Flood Fill
//------------------------------

//explicit graph
const int DFS_WHITE = -1;

file:///C:/Users/moazz/Desktop/template.cpp 11/13
6/15/25, 1:12 AM template.cpp
vector<int> dfs_num(DFS_WHITE,n);
void floodfill(int u, int color) {
dfs_num[u] = color;
for (int v : g[u]) {
if (dfs_num[v] == DFS_WHITE) {
floodfill(v, color);
}
}
}

//implicit graph
int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
const char EMPTY = '*';
int floodfill(int r, int c, char color) {
if (r < 0 || r >= R || c < 0 || c >= C) return 0; // outside grid
if (grid[r][c] != EMPTY) return 0; // cannot be colored
grid[r][c] = color;
int ans = 1;
rep(i,0,4) ans += floodfill(r + dirs[i][0], c + dirs[i][1], color);
return ans;
}

------------------------------------------------------------------------------------------
-----------------------------------Brute Force--------------------------------------------
------------------------------------------------------------------------------------------

/* =============================== */
/* Try all 2^n subsets of n items */
/* =============================== */
void all_subsets(vector<int> items) {
int n = vals.size();
int times = (1 << n);
vector<int> bits(n, 0)
while(times-- > 0) {
do_something(bits)
// generate next set's bit representation
int i = 0, carry = 1;
while (i < n) {
in[i] += carry;
if (in[i] <= 1)
carry = 0;
else
in[i] = 0;
i++;
}

file:///C:/Users/moazz/Desktop/template.cpp 12/13
6/15/25, 1:12 AM template.cpp
}
}

/* ========================================= */
/* Split n items into k containers optimally */
/* ========================================= */
int capacities[MAXN];
int N;
// Return cost of storing n items in i-th container
storage_cost(int i, int n);
// Find best way to split n items among containers
// from index i to N-1. For simplicity, the total
// remaining capacity is carried along.
int search_splits(int i, int n, int tot_cap) {
if (i >= N) return 0;
int min_k = max(0, n - (tot_cap - capacities[i]));
int max_k = min(n, capacities[i]);
int min_cost = INT_MAX;
rep(k, min_k, max_k) {
min_cost = min(min_cost,
storage_cost(i, k) +
search_splits(i+1, n-k, tot_cap - capacities[i]);
)

}
}
int best_split(int n) {
int tot_cap = 0;
rep(i,0,N-1) tot_cap += capacities[i];
return search_splits(0,n,tot_cap);
}

file:///C:/Users/moazz/Desktop/template.cpp 13/13

You might also like