Skip to content

Instantly share code, notes, and snippets.

@snorfalorpagus
Created March 8, 2016 17:50
Show Gist options
  • Select an option

  • Save snorfalorpagus/c7e667cc3b130add8e3c to your computer and use it in GitHub Desktop.

Select an option

Save snorfalorpagus/c7e667cc3b130add8e3c to your computer and use it in GitHub Desktop.
GLPK minimum flow problem
/*
Simple example of minimum cost flow problem in GLPK
To build and run:
$ gcc -o example -lglpk example.c
$ ./example
ret = 0; sol = 25
flow = 5
*/
#include <stdio.h>
#include <stdlib.h>
#include <glpk.h>
typedef struct { double rhs; } v_data;
typedef struct { double low, cap, x, rc; int cost; } a_data;
#define node(v) ((v_data *)((v)->data))
#define arc(a) ((a_data *)((a)->data))
int main(void) {
glp_graph *G;
glp_vertex *v;
glp_arc *a;
// offsets of node data
int v_rhs = sizeof(double)*0;
// offsets for arc data
int a_low = sizeof(double)*0;
int a_cap = sizeof(double)*1;
int a_cost = sizeof(double)*2;
int a_x = sizeof(double)*2;
int a_rc = sizeof(double)*3;
int crash = 0;
double sol;
int ret;
G = glp_create_graph(sizeof(v_data), sizeof(a_data));
glp_add_vertices(G, 2);
a = glp_add_arc(G, 1, 2);
node(G->v[1])->rhs = 5; // input 5 units to the network
node(G->v[2])->rhs = -5; // output 5 units from the network
arc(a)->cap = 100;
arc(a)->cost = 2; // MUST be integer, even though stored in a double
ret = glp_mincost_relax4(G, v_rhs, a_low, a_cap, a_cost, crash, &sol, a_x, a_rc);
printf("ret = %d; sol = %5g\n", ret, sol);
printf("flow = %5g\n", arc(a)->x);
glp_delete_graph(G);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment