# MinCostMaxFlow implementation is not fast enough

I'm trying to solve this problem:

A root tree is a directed acyclic graph that contains one node (root), from which there is exactly one path to any other node.

A root tree is binary if each node has at most two outgoing arcs.

When a binary tree is painted on the plane, all arcs should be directed from top to bottom. That is, each arc going from $u$ to $v$ must meet the condition $y_u$ > $y_v$.

You've been given the coordinates of all tree nodes. Your task is to connect these nodes by arcs so as to get the binary root tree and make the total length of the arcs minimum. All arcs of the built tree must be directed from top to bottom.

This problem can be solved by finding the maximum flow of the minimum cost on the specified network.

Here is my Java realization:

import java.io.IOException;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

public class Main {

private static StreamTokenizer in;

public static void main(String[] args) {
int vertices = nextInt();
int[][] points = new int[vertices];
for (int i=0; i<vertices; i++) {
points[i] = nextInt();
points[i] = nextInt();

}
Graph graph = new Graph(2*vertices+2);
for (int i=0; i<vertices; i++) {
}
for (int i=0; i<vertices; i++) {
for (int j=0; j<vertices; j++) {
if (points[i] < points[j]) {
double rast = Math.sqrt((points[i] - points[j]) * (points[i] - points[j]) + (points[i] - points[j]) * (points[i] - points[j]));
}
}
}
double[] flow = graph.getMaxFlow();
if (flow < vertices-1) {
System.out.println("-1");
} else {
System.out.println(flow);
}
}

private static int nextInt() {
try {
in.nextToken();
} catch (IOException e) {
}
return (int) in.nval;
}

}

class Graph {

int vertices;
boolean found[];
double cap[][], flow[][], cost[][], distance[], pi[];
int prev[];
GraphComparator comparator;
PriorityQueue<Integer> queue;

int s = 0, t;

static double INF = Double.MAX_VALUE/2 - 1;

public Graph(int vertices) {
this.vertices = vertices;
cap = new double[vertices][vertices];
flow = new double[vertices][vertices];
cost = new double[vertices][vertices];
prev = new int[vertices];
distance = new double[vertices+1];
pi = new double[vertices];
found = new boolean[vertices];
t = vertices-1;
for (int i=0; i<vertices; i++) {
}
comparator = new GraphComparator(vertices, this);
queue = new PriorityQueue<Integer>(comparator);
}

public void addEdge(int from, int to, int capacity, double cost) {
this.cap[from][to] = capacity;
this.cost[from][to] = cost;
}

boolean getRoute() {
comparator.reset();
Arrays.fill(found, false);
Arrays.fill(distance, INF);
distance[s] = 0;
int now = s;
while (queue.size() != 0) {
now = queue.poll();
found[now] = true;
if (found[k]) continue;
if (flow[k][now] != 0) {
double val = distance[now] + pi[now] - pi[k] - cost[k][now];
if (distance[k] > val) {
distance[k] = val;
prev[k] = now;
}
}
if (flow[now][k] < cap[now][k]) {
double val = distance[now] + pi[now] - pi[k] + cost[now][k];
if (distance[k] > val) {
distance[k] = val;
prev[k] = now;
}
}
}
}
for (int k = 0; k < vertices; k++)
pi[k] = Math.min(pi[k] + distance[k], INF);
return found[t];
}

double[] getMaxFlow() {

double totalFlow = 0, totalCost = 0;
while (getRoute()) {
double min = INF;
for (int x = t; x != s; x = prev[x])
min = Double.min(min, flow[x][prev[x]] != 0 ? flow[x][prev[x]] :
cap[prev[x]][x] - flow[prev[x]][x]);
for (int x = t; x != s; x = prev[x]) {
if (flow[x][prev[x]] != 0) {
flow[x][prev[x]] -= min;
totalCost -= min * cost[x][prev[x]];
} else {
flow[prev[x]][x] += min;
totalCost += min * cost[prev[x]][x];
}
}
totalFlow += min;
}

return new double[]{ totalFlow, totalCost };
}

}

class GraphComparator implements Comparator<Integer> {

int n;
double[] savedWeights;
Graph graph;

public GraphComparator(int n, Graph graph) {
this.n = n;
this.graph = graph;
savedWeights = new double[n];
reset();
}

public void reset() {
Arrays.fill(savedWeights, Double.MAX_VALUE);
}

@Override
public int compare(Integer arg0, Integer arg1) {
if (savedWeights[arg0] > graph.distance[arg0]) {
savedWeights[arg0] = graph.distance[arg0];
}
if (savedWeights[arg1] > graph.distance[arg1]) {
savedWeights[arg1] = graph.distance[arg1];
}
return Double.compare(savedWeights[arg0], savedWeights[arg1]);
}
}


But it doesn't pass because of the time limit. How can I make it run faster?

• Have you tried profiling it? – Emily L. Nov 12 '14 at 16:11

Good candidates for enhancing performance in algorithms like this is to reduce the number of objects you use. In this case, that primarily means limiting the use of wrapper objects in favour of primitives.

I pre-generated 500 vertices randomly to use as a consistent stress test, which your implementation managed to solve in about 8700ms (give or take 100ms) on my laptop. I'll use that as baseline.

L106: for (Integer k: adj.get(now)) -- Declaring k as an int cut running time by about 10%, down to 7800ms.

L62: ArrayList<ArrayList<Integer>> adj -- Changing adj to be an int[vertices][] with simplistic array-copy-and-add operations took another 40% cut out of running time, down to 4800ms. I imagine some smart sizing could do more, but will add complexity.

Defining your constants as final tweaked performance by another 5%, down to 4550ms.

(There were some other minor tweaks I've tried, but nothing that gave an appreciable performance increase for the additional code complexity / bug odds.)

On an API usage note: maybe java.util.Scanner is a better choice than java.io.StreamTokenizer for reading your vertices:
final Scanner scanner = new Scanner(System.in);

• s is source in graph network, t is sink. pi is array of potentials for Dijkstra algo I use to find the shortest path. – michaeluskov Nov 15 '14 at 23:22