1
\$\begingroup\$

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.InputStreamReader;
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) {
            in = new StreamTokenizer(new InputStreamReader(System.in));
            int vertices = nextInt();
            int[][] points = new int[vertices][2];
            for (int i=0; i<vertices; i++) {
                points[i][0] = nextInt();
                points[i][1] = nextInt();

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

        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[];
        ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>();
        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;
            adj = new ArrayList<ArrayList<Integer>>(vertices);
            for (int i=0; i<vertices; i++) {
                adj.add(new ArrayList<Integer>());
            }
            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;
            adj.get(from).add(to);
            adj.get(to).add(from);
        }

        boolean getRoute() {
            comparator.reset();
            Arrays.fill(found, false);
            Arrays.fill(distance, INF);
            distance[s] = 0;
            int now = s;
            queue.add(s);
            while (queue.size() != 0) {
                now = queue.poll();
                found[now] = true;
                for (Integer k: adj.get(now)) {
                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;
                    queue.add(k);
                    }
                }
                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;
                    queue.add(k);
                    }
                }
            }
            }
            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?

\$\endgroup\$
  • 2
    \$\begingroup\$ Have you tried profiling it? \$\endgroup\$ – Emily L. Nov 12 '14 at 16:11
4
\$\begingroup\$

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.)

Total savings: about 45%.

Speaking of complexity, I found the code a bit hard to follow—s, t, pi[] ?—without studying the underlying algorithm, so I haven't really hunted for algorithmic or implementation shortcuts.

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);
final int count = scanner.nextInt();
for ( int i = 0; i < count; i++ ) {
    final int x = scanner.nextInt();
    final int y = scanner.nextInt();
}
\$\endgroup\$
  • \$\begingroup\$ s is source in graph network, t is sink. pi is array of potentials for Dijkstra algo I use to find the shortest path. \$\endgroup\$ – michaeluskov Nov 15 '14 at 23:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.