filename stringlengths 7 140 | content stringlengths 0 76.7M |
|---|---|
code/graph_algorithms/src/floyd_warshall_algorithm/floyd_warshall_algorithm.py | """ Part of Cosmos by OpenGenus Foundation """
INF = 1000000000
def floyd_warshall(vertex, adjacency_matrix):
# calculating all pair shortest path
for k in range(0, vertex):
for i in range(0, vertex):
for j in range(0, vertex):
# relax the distance from i to j by allowin... |
code/graph_algorithms/src/ford_fulkerson_maximum_flow/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/ford_fulkerson_maximum_flow/ford_fulkerson_maximum_flow.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <iostream>
#include <string.h>
using namespace std;
#define N 7
#define INF 9999999
// flow network
int Flow[N][N];
// visited array
bool visited[N];
// original flow network graph shown in the above example
//0 1 2 3 4 5 6
int graph[N][N] = {
{ 0, 5, 4... |
code/graph_algorithms/src/ford_fulkerson_maximum_flow/ford_fulkerson_maximum_flow_using_bfs.cpp | #include <iostream>
// Part of Cosmos by OpenGenus Foundation //
#include <limits.h>
#include <string.h>
#include <queue>
using namespace std;
#define V 6
/* Returns true if there is a path from source 's' to sink 't' in
* residual graph. Also fills parent[] to store the path */
bool bfs(int rGraph[V][V], int s, i... |
code/graph_algorithms/src/ford_fulkerson_maximum_flow/ford_fulkerson_maximum_flow_using_bfs.java | // Part of Cosmos by OpenGenus Foundation
import java.util.LinkedList;
import java.lang.Exception;
class FordFulkersonUsingBfs {
static final int V = 6;
boolean bfs(int rGraph[][], int s, int t, int parent[]) {
/*
* Create a visited array and mark all vertices as not
* visited
*/... |
code/graph_algorithms/src/ford_fulkerson_maximum_flow/ford_fulkerson_maximum_flow_using_bfs.py | """
Part of Cosmos by OpenGenus Foundation
"""
from collections import defaultdict
# This class represents a directed graph using adjacency matrix representation
class Graph:
def __init__(self, graph):
self.graph = graph # residual graph
self.ROW = len(graph)
# self.COL = len(gr[0])
... |
code/graph_algorithms/src/graph_coloring/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/graph_coloring/graph_coloring.cpp | #include <iostream>
#include <list>
using namespace std;
// A class that represents an undirected graph
class Graph
{
int V; // No. of vertices
list<int> *adj; // A dynamic array of adjacency lists
public:
// Constructor and destructor
Graph(int V)
{
this->V = V; adj = new list<int>[V];
... |
code/graph_algorithms/src/graph_coloring/graph_coloring.java | import java.util.*;
public class Coloring {
int minColors;
int[] bestColoring;
public int minColors(boolean[][] graph) {
int n = graph.length;
bestColoring = new int[n];
int[] id = new int[n + 1];
int[] deg = new int[n + 1];
for (int i = 0; i <= n; i++)
id[i] = i;
bestColoring = new int[n];
int r... |
code/graph_algorithms/src/graph_coloring/graph_coloring_greedy.py | from collections import defaultdict
class Graph:
def __init__(self, V, directed=False):
self.V = V
self.directed = directed
self.graph = defaultdict(list)
def add_edge(self, a, b):
self.graph[a].append(b)
if not self.directed:
self.graph[b].append(a)
... |
code/graph_algorithms/src/hamiltonian_cycle/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/hamiltonian_cycle/hamiltonian_cycle.java | import java.util.Scanner;
class HamiltonCycle {
final static int MAX = 10;
static int NO_VER = MAX;
int path[];
public static void main(String args[]) {
HamiltonCycle hamiltonian = new HamiltonCycle();
Scanner in = new Scanner(System.in);
System.out.println("Backtracking Hamilt... |
code/graph_algorithms/src/hamiltonian_cycle/hamiltonian_cycle.py | # Part of Cosmos by OpenGenus Foundation
# Python program for solution of
# hamiltonian cycle problem
class Graph:
def __init__(self, vertices):
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
self.V = vertices
""" Check if this vertex is an adjacent vertex
... |
code/graph_algorithms/src/hamiltonian_path/hamiltonian_path.cpp | #include <iostream>
#include <vector>
#include <bitset>
#include <cmath>
#include <cstdlib>
#include <cstring>
using namespace std;
const int MAXN = 8000;
const int INF = (int)1e9;
int n, m, *deg, *par, tl = -1;
bool *used;
vector <vector <int>> G;
inline void count_degs()
{
for (int i = 0; i < n; i++)
... |
code/graph_algorithms/src/hopcroft_karp_algorithm/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/johnson_algorithm_shortest_path/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/johnson_algorithm_shortest_path/johnson_algorithm_shortest_path.py | # Part of Cosmos by OpenGenus Foundation
"""
def Johnsons():
data = list()
source = list()
destination = list()
edgecost = list()
test = 0
vertices = 0
edges = 0
data = readfile()
vertexlist = list()
distance = list()
vertices, edges, source, destination, edgecost, vertexlis... |
code/graph_algorithms/src/karger_minimum_cut/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/karger_minimum_cut/karger_minimum_cut.java | /*
Sample Input
8
1 2 4 3
2 1 3 4 5
3 1 2 4
4 3 1 2 7
5 2 6 8 7
6 5 7 8
7 4 5 6 8
8 7 6 5
Here, first number is the node number and the following numbers in each row are it's adjacent rows.
Sample Output
Minimum Cut=2
*/
import java.lang.*;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
publ... |
code/graph_algorithms/src/kruskal_minimum_spanning_tree/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/kruskal_minimum_spanning_tree/kruskal_minimum_spanning_tree.c | // Part of Cosmos by OpenGenus Foundation
#include<stdio.h>
#include<stdlib.h>
#define VAL 999
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
// union - find
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
... |
code/graph_algorithms/src/kruskal_minimum_spanning_tree/kruskal_minimum_spanning_tree.cpp | #include <iostream>
#include <vector>
#include <algorithm>
// Part of Cosmos by OpenGenus Foundation
int n, dj[100], rank[100]; //disjoint set
int findset(int a)
{
if (dj[a] != a)
return dj[a] = findset(dj[a]);
else
return a;
}
bool sameset(int a, int b)
{
return findset(a) == findset(b);
}... |
code/graph_algorithms/src/kruskal_minimum_spanning_tree/kruskal_minimum_spanning_tree.java | /* Java program for Kruskal's algorithm to find Minimum
* Spanning Tree of a given connected, undirected and
* weighted graph
*/
import java.util.*;
import java.lang.*;
import java.io.*;
class Graph
{
// A class to represent a graph edge
class Edge implements Comparable<Edge>
{
int src, dest, ... |
code/graph_algorithms/src/kruskal_minimum_spanning_tree/kruskal_minimum_spanning_tree.py | from collections import defaultdict
# Part of Cosmos by OpenGenus Foundation
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def addEdge(self, u, v, w):
self.graph.append([u, v, w])
def find(self, parent, i):
if parent[i] == i:
retu... |
code/graph_algorithms/src/kuhn_maximum_matching/kuhn_maximum_matching.cpp | /*
* BY:- https://github.com/alphaWizard
*
* algorithm:- finds maximum bipartite matching for a given bipartite graph
* by taking input number of nodes(n) and number of edges(m)
*
* Part of Cosmos by OpenGenus Foundation
*/
#include <iostream>
#include <vector>
std::vector<int> adj[10000];
bool mark[1... |
code/graph_algorithms/src/kuhn_munkres_algorithm/kuhn_munkres_algorithm.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* Kuhn-Munkres algorithm: find the perfect matching in a balanced and weighted bipartite graph
* that gives the maximum sum of weights.
*/
#include <memory>
#include <vector>
#include <type_traits>
#include <limits>
#include <algorithm>
#include <iostream>
#include <in... |
code/graph_algorithms/src/left_view_binary_tree/left_view_binary_tree.cpp | #include <iostream>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
struct node
{
int d;
node *left;
node *right;
};
struct node* newnode(int num)
{
node *temp = new node;
temp->d = num;
temp->left = temp->right = NULL;
return temp;
}
void lefttree(struct node *root, int lev... |
code/graph_algorithms/src/left_view_binary_tree/left_view_binary_tree.java | // Part of Cosmos by OpenGenus Foundation
// This class prints the left nodes of a binary tree
class Node {
int data;
Node left;
Node right;
public Node(int node) {
data = node;
left = right = null;
}
}
class BinaryTree {
Node root; // Define root node
int max_level ... |
code/graph_algorithms/src/left_view_binary_tree/left_view_binary_tree.py | # Part of Cosmos by OpenGenus Foundation
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Recursive function pritn left view of a binary tree
def leftViewUtil(root, level, max_level):
... |
code/graph_algorithms/src/longest_path_directed_acyclic_graph/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/longest_path_directed_acyclic_graph/longest_path_directed_acyclic_graph.cpp | #include <iostream>
#include <vector>
#include <algorithm>
/* Part of Cosmos by OpenGenus Foundation */
void dfs(int v, std::vector<std::vector<int>> &g, std::vector<int> &dp)
{
if (dp[v])
return;
dp[v] = 1;
for (int u : g[v])
{
dfs(u, g, dp);
dp[v] = std::max(dp[v], dp[u] + 1... |
code/graph_algorithms/src/lowest_common_ancestor/lowest_common_ancestor.cpp | #include <iostream>
#include <vector>
#include <array>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
// Problem Statement
/*
* Given a tree with n nodes
* Your task is to process q queries of the following form:
* who is the lowest common ancestor of nodes a and b in the tree?
*
* The lowest com... |
code/graph_algorithms/src/matrix_transformation/matrix_transformation.swift | // Part of Cosmos by OpenGenus Foundation
import Foundation
class MatrixTransformation {
func rotate<T>(_ matrix: inout [[T]]) {
guard matrix.count > 0 && matrix.count == matrix[0].count else {
return
}
// 1 2 3 7 8 9 7 4 1
// 4 5 6 => 4 5 6 => 8 5 2
... |
code/graph_algorithms/src/maximum_bipartite_matching/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/maximum_bipartite_matching/maximum_bipartite_matching.py | # Part of Cosmos by OpenGenus Foundation
""" Python program to find maximal Bipartite matching.
This is taking corresponding to graph of applicants and
their corresponding job positions.
"""
class Graph:
def __init__(self, graph):
self.graph = graph # residual graph
self.ppl = len(graph... |
code/graph_algorithms/src/maximum_edge_disjoint_paths/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/minimum_s_t_cut/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/negative_cycle_finding/negativeCycleFinding.cpp | struct Edge {
ll a, b, cost;
};
int n, m;
vector<Edge> edges;
const ll INF = 1e9 + 5;
void solve(){
vector<ll> d(n);
vector<int> p(n, -1);
int x;
for (int i = 0; i < n; ++i) {
x = -1;
for (Edge e : edges) {
if (d[e.a] + e.cost < d[e.b]) {
d[e.b] = d[e.a]... |
code/graph_algorithms/src/postorder_from_inorder_and_preorder/postorder_from_inorder_and_preorder.cpp | #include <iostream>
using namespace std;
int search(int in[], int k, int n)
{
for (int i = 0; i < n; i++)
if (in[i] == k)
return i;
return -1;
}
void postorder(int in[], int pre[], int n)
{
int root = search(in, pre[0], n);
if (root != 0)
postorder(in, pre + 1, root);
... |
code/graph_algorithms/src/prim_minimum_spanning_tree/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/prim_minimum_spanning_tree/prim_minimum_spanning_tree.c | /*
* Part of Cosmos by OpenGenus Foundation
*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// Single node of the graph
typedef struct node
{
int vert;
int weight;
struct node *next;
} node;
// Vertex of the graph
typedef struct vertex
{
int key;
int pos;
} vertex;
// Establish a connection of gi... |
code/graph_algorithms/src/prim_minimum_spanning_tree/prim_minimum_spanning_tree.cpp | #include <iostream>
#include <vector>
#include <utility>
#include <set>
using namespace std;
typedef long long ll;
// Part of Cosmos by OpenGenus Foundation
const int MAXN = 1e4 + 5;
bool vis[MAXN];
int n, m;
vector<pair<ll, int>> adj[MAXN]; // for every vertex store all the edge weight and the adjacent vertex to i... |
code/graph_algorithms/src/prim_minimum_spanning_tree/prim_minimum_spanning_tree.py | # A Python program for Prim's Minimum Spanning Tree (MST) algorithm.
# The program is for adjacency matrix representation of the graph
# Part of Cosmos by OpenGenus Foundation
class Python:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)] for row in ran... |
code/graph_algorithms/src/push_relabel/push_relabel.cpp | #include <vector>
#include <queue>
// push as much excess flow as possible from f to t
void push(std::vector<std::vector<int>> graph, std::vector<std::vector<int>>& flow,
std::vector<std::vector<int>>& residual, std::vector<int>& excess, int f, int t)
{
if (excess[f] <= 0)
{
std::cerr << "ex... |
code/graph_algorithms/src/redundant-connection/redundant_connection.cpp | /*
* Part of Cosmos by OpenGenus foundation
*
* Redundant Connection
*
* Description
*
* Return an edge that can be removed from an undirected graph so that the resulting graph is a tree of N nodes
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> parent; //dis... |
code/graph_algorithms/src/shortest_path_k_edges/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/steiner_tree/steiner_tree.java | public class SteinerTree {
public static int minLengthSteinerTree(int[][] g, int[] verticesToConnect) {
int n = g.length;
int m = verticesToConnect.length;
if (m <= 1)
return 0;
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
g[i][j] = Math.min(g[i][j], g[i]... |
code/graph_algorithms/src/strongly_connected_components/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/strongly_connected_components/strongly_connected_components.cpp | #include <iostream>
#include <list>
#include <stack>
using namespace std;
class Graph
{
int V; // No. of vertices
list<int> *adj; // An array of adjacency lists
// Fills Stack with vertices (in increasing order of finishing
// times). The top element of stack has the maximum finishing
// time
void f... |
code/graph_algorithms/src/strongly_connected_components/strongly_connected_components.py | # Part of Cosmos by Open Genus foundation
# Python implementation of Kosaraju's algorithm to print all SCCs
from collections import defaultdict
# This class represents a directed graph using adjacency list representation
class Graph:
def __init__(self, vertices):
self.V = vertices # No. of vertices
... |
code/graph_algorithms/src/tarjan_algorithm_strongly_connected_components/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/tarjan_algorithm_strongly_connected_components/tarjan_algorithm_strongly_connected_components.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
* Tarjan algorithm.
*
* You will need the data-structure located in
* https://github.com/OpenGenus/cosmos/tree/master/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C
* to use this algorithm.
*/
#include "lg... |
code/graph_algorithms/src/topological_sort/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/topological_sort/kahn_algo_unique_toposort.cpp | // Sample problem for using this algorithm - UVA 11060 Beverages
#include <bits/stdc++.h>
#define all(a) a.begin(), a.end()
#define ll long long
#define inp(a) scanf("%d", &a)
#define out(a) printf("%d\n", a)
#define inp2(a) scanf("%lld", &a)
#define out2(a) printf("%lld\n", a)
#define arrinput(a, n) for (int i = 0; i ... |
code/graph_algorithms/src/topological_sort/kahn_algorithm_basic.cpp | /*
* Implementation of the Kahn's algorithm
* for topological sort in a directed acyclic graph
*/
#include <iostream>
#include "bits/stdc++.h"
using namespace std;
queue<int> q, q2;
long long n = 100000;
int v, e, v1, v2, visited[10000], level[100000], indegree[100000];
vector<int> g[100000];
void bfs(int i)
{
w... |
code/graph_algorithms/src/topological_sort/print_all_topological_sorts.cpp | #include <iostream>
#include <vector>
using namespace std;
class Graph {
vector<vector<int>> graph;
vector<int> indegree;
public:
Graph (int);
void insert_egde (int, int);
void all_topo_sorts ();
void all_topo_sorts_helper (vector<int> &, vector<bool> &);
};
Graph :: Graph (int v)
{
graph.... |
code/graph_algorithms/src/topological_sort/topological_sort.c | /*
* Part of Cosmos by OpenGenus Foundation.
* Author : ABDOUS Kamel
* Topological sort based on depth-first search.
*
* You will need the data-structure located in
* https://github.com/OpenGenus/cosmos/tree/master/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C
* to use this... |
code/graph_algorithms/src/topological_sort/topological_sort.cpp | /* Part of Cosmos by OpenGenus Foundation */
#include <cstdio>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
using namespace std;
#define NUM_V 100005
vector<int> adjList[NUM_V + 5];
int inDegree[NUM_V + 5];
int vertex;
vector<int> toposort()
{
vector<int> result;
queue<int> q;
... |
code/graph_algorithms/src/topological_sort/topological_sort.hs | module Topological where
import Data.List
-- Part of Cosmos by OpenGenus
-- Note: this implementation is not the most efficient.
-- With a better DAG datastructure, this would be O(V+E)
-- But if the number of sources of the graph is generally low,
-- this implementation approximates that.
topo' [] _ _ = []
topo' (r... |
code/graph_algorithms/src/topological_sort/topological_sort.js | /**
* Part of Cosmos by OpenGenus
* Javascript program to find topological Sort order of a Directed Acyclic Graph.
* Topological sorting for Directed Acyclic Graph (DAG) is a linear
* ordering ofvertices such that for every directed edge uv,1
* vertex u comes before v in the ordering.
*/
class Graph {
construc... |
code/graph_algorithms/src/topological_sort/topological_sort.py | """ Part of Cosmos by OpenGenus Foundation """
from collections import deque
NUM_V = 100005
adj_list = [[] for i in range(0, NUM_V)]
in_degree = [0 for i in range(0, NUM_V)]
def toposort():
result = []
q = deque()
for i in range(1, vertex + 1):
# if no incoming degree, add to queue
if i... |
code/graph_algorithms/src/topological_sort/topological_sort_adjacency_list.java | /**
* This topological sort implementation takes an adjacency list of an acyclic graph and returns
* an array with the indexes of the nodes in a (non unique) topological order
* which tells you how to process the nodes in the graph. More precisely from wiki:
* A topological ordering is a linear ordering of its vert... |
code/graph_algorithms/src/topological_sort/topological_sort_adjacency_list2.java | /**
* This topological sort implementation takes an adjacency list of an acyclic graph and returns
* an array with the indexes of the nodes in a (non unique) topological order
* which tells you how to process the nodes in the graph. More precisely from wiki:
* A topological ordering is a linear ordering of its vert... |
code/graph_algorithms/src/topological_sort/topological_sort_adjacency_matrix.java | /**
* This Topological sort takes an adjacency matrix of an acyclic graph and returns
* an array with the indexes of the nodes in a (non unique) topological order
* which tells you how to process the nodes in the graph. More precisely from wiki:
* A topological ordering is a linear ordering of its vertices such tha... |
code/graph_algorithms/src/topological_sort/topological_sort_adjacency_matrix2.java | /**
* This Topological sort takes an adjacency matrix of an acyclic graph and returns
* an array with the indexes of the nodes in a (non unique) topological order
* which tells you how to process the nodes in the graph. More precisely from wiki:
* A topological ordering is a linear ordering of its vertices such tha... |
code/graph_algorithms/src/transitive_closure_graph/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/transitive_closure_graph/transitive_closure_graph.cpp | #include <stdio.h>
#include <iostream>
using namespace std;
void printSolution(int reach[][4])
{
cout << "Following matrix is transitive closure of the given graph\n";
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
cout << reach[i][j];
cout << endl;
}
}
void transi... |
code/graph_algorithms/src/transitive_closure_graph/transitive_closure_graph.py | # Python program to print transitive closure of a graph
# Part of Cosmos by OpenGenus Foundation
from collections import defaultdict
# This class represents a directed graph using adjacency list representation
class Graph:
def __init__(self, vertices):
# No. of vertices
self.V = vertices
#... |
code/graph_algorithms/src/transitive_closure_graph/transitive_closure_graph_floyd_warshall.cpp | #include <iostream>
#include <vector>
#include <bitset>
/* Part of Cosmos by OpenGenus Foundation */
// Floyd-Warshall algorithm. Time complexity: O(n ^ 3)
void transitive_closure_graph(std::vector<std::vector<int>> &graph)
{
int n = (int) graph.size();
for (int k = 0; k < n; k++)
for (int i = 0; i < ... |
code/graph_algorithms/src/transitive_closure_graph/transitive_closure_graph_powering.cpp | #include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
/// utility function to print the transitive closure matrix
void print_transitive_closure(int** output, int num_nodes)
{
cout << endl;
for(int i=0;i<num_nodes;i++)
{
for(int j=0;j<num_nodes;j++)
{
cout ... |
code/graph_algorithms/src/transitive_closure_graph/transitive_closure_graph_powering_improved.cpp | #include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
/// utility function to print the transitive closure matrix
void print_transitive_closure(int** output, int num_nodes)
{
cout << endl;
for(int i=0;i<num_nodes;i++)
{
for(int j=0;j<num_nodes;j++)
{
cout ... |
code/graph_algorithms/src/travelling_sales_man_dp/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus)
|
code/graph_algorithms/src/travelling_sales_man_dp/travelling_salesman_dp.cpp | #include <bits/stdc++.h>
using namespace std;
class brute_force
{
public:
int shortest_path_sum(int** edges_list, int num_nodes)
{
int source = 0;
vector<int> nodes;
for(int i=0;i<num_nodes;i++)
{
if(i != source)
{
nodes.push_back(i);
... |
code/graph_algorithms/src/travelling_salesman_branch&bound/tsp_branch_bound.cpp | #include <bits/stdc++.h>
using namespace std;
// number of total nodes
#define N 5
#define INF INT_MAX
class Node
{
public:
vector<pair<int, int>> path;
int matrix_reduced[N][N];
int cost;
int vertex;
int level;
};
Node* newNode(int matrix_parent[N][N], vector<pair<int, int>> const &path,int leve... |
code/graph_algorithms/src/travelling_salesman_mst/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/src/travelling_salesman_mst/travelling_salesman.c | #include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <time.h>
#define MAX_N 21
#define MAX_E (MAX_N * (MAX_N - 1)) / 2
#define MAX_MASK (1 << MAX_N)
#define MAX_W 100
#define NB_ITER 20
int N, fullmask, dp[MAX_N][MAX_MASK];
int G[MAX_N][MAX_N];
/* Result of PVC is stored here. Each element correspond ... |
code/graph_algorithms/src/travelling_salesman_mst/travelling_salesman.cpp | #include <iostream>
#include <vector>
const int MAX = 2000000000;
const int MAX_NODES = 20;
int optimalWayLength[1 << MAX_NODES][MAX_NODES];
bool was[1 << MAX_NODES][MAX_NODES];
int cameFrom[1 << MAX_NODES][MAX_NODES];
int distances[MAX_NODES][MAX_NODES];
int n;
int findAns (int last, int mask)
{
if (mask =... |
code/graph_algorithms/src/travelling_salesman_mst/travelling_salesman.py | # Part of Cosmos by OpenGenus Foundation
def solve_tsp_dynamic(points):
# calc all lengths
all_distances = [[length(x, y) for y in points] for x in points]
# initial value - just distance from 0 to every other point + keep the track of edges
A = {
(frozenset([0, idx + 1]), idx + 1): (dist, [0, i... |
code/graph_algorithms/src/vertex_cover/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/graph_algorithms/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/graph_algorithms/test/floyd_warshall_graph/floyd_warshal_test.go | package graph
import (
"math"
"testing"
)
const float64EqualityThreshold = 1e-9
//almostEqual subtracts two float64 variables and returns true if they differ less then float64EqualityThreshold
//reference: https://stackoverflow.com/a/47969546
func almostEqual(a, b float64) bool {
return math.Abs(a-b) <= float64Eq... |
code/graph_algorithms/test/matrix_transformation/test_matrix_transformation.swift | // Part of Cosmos by OpenGenus Foundation
import Foundation
class TestMatrixTransformation {
let mt = MatrixTransformation()
var matrix: [[Int]] = []
let m0: [[Int]] = []
let m1 = [[1]]
let m2 = [[1, 2],
[3, 4]]
let m4 = [[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
... |
code/graph_algorithms/test/push_relabel/test_push_relabel.cpp | #define CATCH_CONFIG_MAIN
#include "../../../../test/c++/catch.hpp"
#include "../../src/push_relabel/push_relabel.cpp"
#include <iostream>
int g_testCounter = 0;
std::vector<std::vector<int>> g_graph;
std::vector<std::vector<int>> g_flow;
int test(int s, int t, bool empty)
{
int k = (empty ? maxFlowEmpty(g_graph... |
code/greedy_algorithms/src/README.md | # Greedy algorithms
> Cosmos: Your personal library of every algorithm and data structure code that you will ever encounter
A greedy algorithm is an algorithmic paradigm that follows the problem solving heuristic of making the locally optimal choice at each stage with the hope of finding a global optimum. In many prob... |
code/greedy_algorithms/src/SplitArrayLargestSum/README.md | # Split Array Largest Sum
Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays.
Write an algorithm to minimize the largest sum among these m subarrays.
### Example 1:
Input: nums = [7,2,5,10,8], m = 2
Output: 18
Expla... |
code/greedy_algorithms/src/SplitArrayLargestSum/SplitArrayLargestSum.cpp | //CODE
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
/*
Parameters:
nums - The input array;
cuts - How many cuts are available (cuts = #groups - 1);
max - The maximum of the (sum of elements in one group);
Return:
Whethe... |
code/greedy_algorithms/src/activity_selection/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/greedy_algorithms/src/activity_selection/activity_selection.c | #include <stdio.h>
#include <stdlib.h>
struct activity
{
int start, finish;
};
int
comparator(const void* s1, const void* s2)
{
return ((struct activity *)s1)->finish > ((struct activity *)s2)->finish;
}
void
print_max_activities(struct activity arr[], int n)
{
qsort(arr, n, sizeof(arr[0]), comparator);
printf(... |
code/greedy_algorithms/src/activity_selection/activity_selection.cpp | #include <algorithm>
#include <iostream>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
// A job has start time, finish time and profit.
struct Activitiy
{
int start, finish;
};
// A utility function that is used for sorting
// activities according to finish time
bool activityCompare(Activitiy s1,... |
code/greedy_algorithms/src/activity_selection/activity_selection.java | // Part of Cosmos by OpenGenus Foundation
// Activity selection problem
import java.io.*;
import java.lang.*;
import java.math.*;
import java.util.*;
class ActivitySelection {
static void activitySelection(List<Activity> activities, int n) {
Collections.sort(activities, new ActivityComparator());
System.out.... |
code/greedy_algorithms/src/activity_selection/activity_selection.py | """
Part of Cosmos by OpenGenus Foundation
Activity Selection Problem
"""
class Activity:
def __init__(self, start, finish):
self.start = start
self.finish = finish
def __lt__(self, other):
return self.finish < other.finish
def __repr__(self):
return "( %s, %s )" % (s... |
code/greedy_algorithms/src/dials_algorithm/dials_algorithm.cpp | // C++ Program for Dijkstra's dial implementation
#include<bits/stdc++.h>
using namespace std;
# define INF 0x3f3f3f3f
// This class represents a directed graph using
// adjacency list representation
class Graph
{
int V; // No. of vertices
// In a weighted graph, we need to store vertex
// and weight pair for ever... |
code/greedy_algorithms/src/dijkstra_shortest_path/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
Collaborative effort by [OpenGenus](https://github.com/opengenus) |
code/greedy_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.c | /*
* From a given vertex in a weighted connected graph, find shortest
* paths to other vertices using Dijkstra's algorithm
*/
#include "stdio.h"
#define infinity 999
void dij(int n, int src, int cost[10][10], int dist[])
{
int i, u, count, flag[10], min;
for(i = 1; i <= n; i++)
flag[i] = 0, dist[i] = cost[s... |
code/greedy_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.cpp | // Implemented by jhbecares based on Dijkstra's algorithm in "Competitive Programming 3"
// Example extracted from problem 10986 - Sending email from UVa Online Judge
/*
* Try with the following data:
* Sample Input
* 3
* 2 1 0 1
* 0 1 100
* 3 3 2 0
* 0 1 100
* 0 2 200
* 1 2 50
* 2 0 0 1
*
* Sample Output
... |
code/greedy_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.java | // Part of Cosmos by OpenGenus Foundation
public class Dijkstra {
// Dijkstra's algorithm to find shortest path from s to all other nodes
public static int [] dijkstra (WeightedGraph G, int s) {
final int [] dist = new int [G.size()]; // shortest known distance from "s"
final int [] pred = new int [G.s... |
code/greedy_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.py | # Part of Cosmos by OpenGenus Foundation
def dijkstra(graph, source):
vertices, edges = graph
dist = dict()
previous = dict()
for vertex in vertices:
dist[vertex] = float("inf")
previous[vertex] = None
dist[source] = 0
Q = set(vertices)
while len(Q) > 0:
u = minim... |
code/greedy_algorithms/src/egyptian_fraction/egyptian_fraction.c | #include <stdio.h>
/*
This is a program to represent a number in terms of it's Egyptian fraction. An Egyptian Fraction is a finitet sum of unit fractions. Any
positive rational number can be represented by sum of unit fractions.
*/
void printEgyptian(int numerator, int denominator)
{
if (denominator == 0 || numera... |
code/greedy_algorithms/src/egyptian_fraction/egyptian_fraction.cpp | #include <iostream>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
void printEgyptian(int numerator, int denominator)
{
if (denominator == 0 || numerator == 0)
return;
if (denominator % numerator == 0)
{
cout << "1/" << denominator / numerator;
return;
}
if ... |
code/greedy_algorithms/src/egyptian_fraction/egyptian_fraction.php |
<?php
// Part of Cosmos by OpenGenus
// PHP program to print a fraction
// in Egyptian Form using Greedy
// Algorithm
function printEgyptian($nr, $dr)
{
// If either numerator or
// denominator is 0
if ($dr == 0 || $nr == 0)
return;
// If numerator divides denominator,
/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.