Beispiel #1
0
  public static void main(String[] args) {
    try {
      Scanner scanner = new Scanner(new FileInputStream("graph.txt"));
      int v = Integer.parseInt(scanner.nextLine());

      int source = Integer.parseInt(scanner.nextLine());

      int sink = Integer.parseInt(scanner.nextLine());

      ListGraph g = new ListGraph(v, source, sink);
      while (scanner.hasNext()) {
        String edgeLine = scanner.nextLine();

        String[] components = edgeLine.split("\\s+");
        assert components.length == 3;
        int i = Integer.parseInt(components[0]);
        int j = Integer.parseInt(components[1]);
        int capacity = Integer.parseInt(components[2]);

        g.addEdge(i, j, capacity);
      }

      System.out.println("Original matrix");
      g.print();

      ListGraph.maxFlow(g);

      g.print();

    } catch (FileNotFoundException e) {
      System.err.println(e.toString());
      System.exit(1);
    }
  }
Beispiel #2
0
  public static void maxFlow(ListGraph g) {
    ListGraph residualG = g.residualGraph();

    LinkedList<DirEdge> path = residualG.getFlowPath();
    while (path != null) {
      // System.out.println("Got path");
      int minCapacity = ListGraph.minCapacityInPath(path);

      assert minCapacity > 0;
      // augment every edge on the path in the original graph
      int head = g.getSource();
      ListIterator it = path.listIterator();
      while (it.hasNext()) {
        DirEdge rEdge = (DirEdge) it.next();
        int tail = rEdge.end;

        DirEdge e = g.getEdge(head, tail);
        e.flow += minCapacity;

        // System.out.println("Augmenting (" + head + "," + tail + ") to be " + e.flow);

        head = tail;
      }

      residualG = g.residualGraph();

      // System.out.println("g:");
      // g.print();

      // System.out.println("Residual graph:");
      // residualG.print();

      path = residualG.getFlowPath();
    }
  }
Beispiel #3
0
  public ListGraph residualGraph() {
    ListGraph residualG = new ListGraph(getNumNodes(), this.source, this.sink);
    for (int i = 0; i < v; i++) {
      ListIterator it = edges.get(i).listIterator();

      while (it.hasNext()) {
        DirEdge edge = (DirEdge) it.next();
        int leftCapacity = edge.capacity - edge.flow;
        if (leftCapacity > 0) residualG.addEdge(i, edge.end, leftCapacity);

        if (edge.flow > 0)
          residualG.addEdge(edge.end, i, edge.flow); // add the reverse direction capacity
      }
    }

    return residualG;
  }