Skip to content

Instantly share code, notes, and snippets.

View rcabreu's full-sized avatar

Roberto Abreu rcabreu

View GitHub Profile
@rcabreu
rcabreu / BIT.cpp
Created February 7, 2013 03:47
C++::data_structures::BinaryIndexedTree
int C[N];
int read(int i) {
int sum = 0;
while (i > 0) {
sum += C[i];
i -= (i & -i);
}
return sum;
}
@rcabreu
rcabreu / SegmentTree.cpp
Last active December 13, 2015 20:58
C++::data_structures::Segment_Tree
class SegmentTree {
private:
vector<int> st;
vector<int> a;
int n;
int left(int p) { return (p << 1); }
int right(int p) { return (p << 1) + 1; }
void initialize(int p, int L, int R) {
if (L == R)
@rcabreu
rcabreu / trie.cpp
Created February 27, 2013 12:33
C++::data_structures::Trie
struct node {
node *children[26];
int words;
int prefixes;
};
struct trie {
node *root;
};
@rcabreu
rcabreu / matrix_exponentiation.cpp
Created March 26, 2013 21:44
C++::algorithms::Matrix Exponentiation
#define DIM 2 // default to 2. Set value according to problem.
struct matrix{
ll a[DIM][DIM];
// constructor. Make an empty array.
matrix() {
memset(a, 0, sizeof(ll) * DIM * DIM);
}
@rcabreu
rcabreu / kmp.cpp
Created June 14, 2013 18:32
C++::algorithms::KMP
vector<int> kmp(string str, string pattern) {
vector<int> T(pattern.size() + 1, -1);
vector<int> matches;
if(pattern.size() == 0) {
matches.push_back(0);
return matches;
}
for(int i = 1; i <= pattern.size(); i++) {
int pos = T[i - 1];
while(pos != -1 && pattern[pos] != pattern[i - 1]) pos = T[pos];
@rcabreu
rcabreu / dijkstra.cpp
Last active July 13, 2024 23:49
C++::algorithms::Dijkstra
#define MAXN 1000
#define INF 1000000009
struct node {
int id;
int d;
int pos;
int p;
node(){}
node(int _id, int _d, int _pos, int _p) {
@rcabreu
rcabreu / suffixarray.cpp
Created June 18, 2013 23:32
C++::algorithms::Suffix_Arrays
const int MAXN = 1 << 21;
string S;
int N, gap;
int sa[MAXN], pos[MAXN], tmp[MAXN], lcp[MAXN];
bool sufCmp(int i, int j){
if (pos[i] != pos[j])
return pos[i] < pos[j];
i += gap;
@rcabreu
rcabreu / exp_by_sq.cpp
Last active March 23, 2020 03:06
C++::algorithms::Fast_Exponentiation
ll fast_expo(ll base, ll expt) {
if (expt == 0) return 1LL;
if (expt == 1) return base;
ll ans = fast_expo(base, expt / 2);
ans = (ans + MOD) % MOD;
ans = (ans * ans + MOD) % MOD;
if (expt & 1LL) ans = (ans * base + MOD) % MOD;
return ans;
}
@rcabreu
rcabreu / gist:6241254
Created August 15, 2013 14:28
C++::templates::DefaultTemplate
#include <algorithm>
#include <cassert>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iomanip>
@rcabreu
rcabreu / UnionFind.cpp
Last active June 7, 2023 19:50
C++::data_structures::UnionFind
class UnionFind {
private:
vector<int> p;
vector<int> rank;
public:
UnionFind(int n) {
rank.assign(n, 0);
p.resize(n);
for (int i = 0; i < n; ++i) p[i] = i;