Skip to content

Instantly share code, notes, and snippets.

@CsengerG
CsengerG / kmp-search.cpp
Last active February 18, 2017 20:05
Knuth-Morris-Pratt: search for a pattern
void kmp(){
int q = 0; // the position in P
int i = 0; // the position in T
while( i < n ){ // go through the entire array
if( P[q+1] == T[i+1] ){ // if a match continues, we increase the positions
q++;
i++;
if( q == m ){ // if q reached m, it means that we have a match
cout << "match from " << i-m+1 << endl;
@CsengerG
CsengerG / kmp-compute-pi.cpp
Last active February 18, 2017 20:02
Knuth-Morris-Pratt: computing the PI array
void computePi(){
pi[1] = 0;
// compute pi[i] for all i
for( int i = 1; i <= m; ++i ){
int w = pi[i];
if ( P[i+1] == P[w+1] ) pi[i+1] = w + 1; // the "first" case
else { // the "second" case
while( w != 0 ){
@CsengerG
CsengerG / find-all-bridges.cpp
Last active December 26, 2015 21:00
Finding all bridges in a graph
vector<int> g[maxn];
int id = 1;
int pre[maxn];// pre[v] is the label for the vertex v
int l[maxn];// l[v] is the lowest label what we can reach from the vertex v
void dfs(int v, int parent){
pre[v] = id++;
l[v] = pre[v];// in the beginning this is the lowest label what we reach from here
@CsengerG
CsengerG / pre-order-traversal.cpp
Last active December 26, 2015 19:39
Pre-order traversal
vector<int> g[maxn];
int pre[maxn];
int id = 1;
void preorder(int v){
pre[v] = id++;
for(int i = 0; i < g[v].size(); ++i){
if( pre[g[v][i]] == 0 ) preorder(g[v][i]);
}
@CsengerG
CsengerG / lowest-common-ancestor.cpp
Last active November 8, 2017 01:35
Lowest common ancestor
// Algorithm for finding the lowest common ancestor of two nodes in a tree
// with O(N log N) preprocessing and O(log N) query time
#include <bits/stdc++.h>
#define ll long long
#define FOR(i,n) for(int i=0;i<n;++i)
#define pb push_back
#define sz size
#define MAXN 100000
@CsengerG
CsengerG / count-components.cpp
Created December 23, 2015 11:43
Count a number of components in a graph
int number_of_components = 0
for(int i=0;i<N;++i){
if(explored[i]==false){
dfs(i);
number_of_components++;
}
}
@CsengerG
CsengerG / dept-first-search.cpp
Created December 23, 2015 11:19
Depth-first search
#include <bits/stdc++.h>
using namespace std;
const int maxn=100000;
vector<int> g[maxn];
bool explored[maxn];
void dfs(int v){
explored[v]=true;
@CsengerG
CsengerG / vectors.cpp
Last active December 22, 2015 16:17
Reading a graph from the standard input in C++
#include<bits/stc++.h>
vector<int> g[MAXN];//Vectors storing our graph
int main(void){
int n;//n - the number of vertexes in our graph
int m;//m - the number of edges in our graph
cin >> n >> m;
for(int i=0;i<m;++i){
int a,b;