+static void optimise(int doprint) {
+ glp_prob *prob = 0;
+ int i, j, totalfrags;
+
+#define HAVE_PRINTED ({ \
+ if (!doprint) { doprint = 1; goto retry_with_print; } \
+ })
+ retry_with_print:
+#define PRINTF if (!doprint) ; else printf /* bodgy */
+
+ for (i=0, totalfrags=0; i<n; i++) {
+ int frags = count_set_adj_bits(adjmatrix[i]);
+ totalfrags += frags;
+ PRINTF("%"PRADJ" ", adjmatrix[i]);
+ double maxminsize = (double)m / frags;
+ if (maxminsize <= best) {
+ PRINTF(" too fine");
+ goto out;
+ }
+ }
+
+ /*
+ * We formulate our problem as an LP problem as follows.
+ * In this file "n" and "m" are the matchstick numbers.
+ *
+ * Each set bit in the adjacency matrix corresponds to taking a
+ * fragment from old match i and making it part of new match j.
+ *
+ * The structural variables (columns) are:
+ * x_minimum minimum size of any fragment (bounded below by 0)
+ * x_morefrag_i_j the amount by which the size of the fragment
+ * i,j exceeds the minimum size (bounded below by 0)
+ *
+ * The auxiliary variables (rows) are:
+ * x_total_i total length for each input match (fixed variable)
+ * x_total_j total length for each output match (fixed variable)
+ *
+ * The objective function is simply
+ * maximise x_minimum
+ *
+ * We use X_ and Y_ to refer to GLPK's (1-based) column and row indices.
+ * ME_ refers to entries in the list of constraint matrix elements
+ * which we build up as we go.
+ */
+
+ prob = glp_create_prob();
+
+ int Y_totals_i = glp_add_rows(prob, n);
+ int Y_totals_j = glp_add_rows(prob, m);
+ int X_minimum = glp_add_cols(prob, 1);
+
+ {
+ int next_matrix_entry = 1; /* wtf GLPK! */
+ int matrix_entries_size = next_matrix_entry + n + m + totalfrags*2;
+ double matrix_entries[matrix_entries_size];
+ int matrix_entries_XY[2][matrix_entries_size];
+
+#define ADD_MATRIX_ENTRY(Y,X) ({ \
+ assert(next_matrix_entry < matrix_entries_size); \
+ matrix_entries_XY[0][next_matrix_entry] = (X); \
+ matrix_entries_XY[1][next_matrix_entry] = (Y); \
+ matrix_entries[next_matrix_entry] = 0; \
+ next_matrix_entry++; \
+ })
+
+ int ME_totals_i__minimum = next_matrix_entry;
+ for (i=0; i<n; i++) ADD_MATRIX_ENTRY(Y_totals_i+i, X_minimum);
+
+ int ME_totals_j__minimum = next_matrix_entry;
+ for (j=0; j<m; j++) ADD_MATRIX_ENTRY(Y_totals_j+j, X_minimum);
+
+ /* \forall_i x_totals_i = m */
+ /* \forall_i x_totals_j = n */
+ for (i=0; i<n; i++) glp_set_row_bnds(prob, Y_totals_i+i, GLP_FX, m,m);
+ for (j=0; j<m; j++) glp_set_row_bnds(prob, Y_totals_j+j, GLP_FX, n,n);
+
+ /* x_minimum >= 0 */
+ glp_set_col_bnds(prob, X_minimum, GLP_LO, 0, 0);
+ glp_set_col_name(prob, X_minimum, "minimum");
+
+ /* objective is maximising x_minimum */
+ glp_set_obj_dir(prob, GLP_MAX);
+ glp_set_obj_coef(prob, X_minimum, 1);
+