Competitive Programming: POJ 2455 – Secret Milking Machine

 

Description

Farmer John is constructing a new milking machine and wishes to keep it secret as long as possible. He has hidden in it deep within his farm and needs to be able to get to the machine without being detected. He must make a total of T (1 <= T <= 200) trips to the machine during its construction. He has a secret tunnel that he uses only for the return trips.

The farm comprises N (2 <= N <= 200) landmarks (numbered 1..N) connected by P (1 <= P <= 40,000) bidirectional trails (numbered 1..P) and with a positive length that does not exceed 1,000,000. Multiple trails might join a pair of landmarks.

To minimize his chances of detection, FJ knows he cannot use any trail on the farm more than once and that he should try to use the shortest trails.

Help FJ get from the barn (landmark 1) to the secret milking machine (landmark N) a total of T times. Find the minimum possible length of the longest single trail that he will have to use, subject to the constraint that he use no trail more than once. (Note well: The goal is to minimize the length of the longest trail, not the sum of the trail lengths.)

It is guaranteed that FJ can make all T trips without reusing a trail.

Input

  • Line 1: Three space-separated integers: N, P, and T
  • Lines 2..P+1: Line i+1 contains three space-separated integers, A_i, B_i, and L_i, indicating that a trail connects landmark A_i to landmark B_i with length L_i.

Output

  • Line 1: A single integer that is the minimum possible length of the longest segment of Farmer John’s route.

Sample Input

7 9 2
1 2 2
2 3 5
3 7 5
1 4 1
4 3 1
4 5 7
5 7 1
1 6 3
6 7 3

Sample Output

5

Hint

Farmer John can travel trails 1 – 2 – 3 – 7 and 1 – 6 – 7. None of the trails travelled exceeds 5 units in length. It is impossible for Farmer John to travel from 1 to 7 twice without using at least one trail of length 5.

Huge input data, scanf is recommended.

Link to problem

Solution below . . .

/*
 * 1. Pick your favorite network flow algorithm. I'm using Dinic but
 * Ford-Fulkerson or other should work as well.
 * 
 * 2. Read and store the edges. Keep track of the longest and shortest. These
 * are the upper and lower bound on the solution.
 * 
 * 3. Starting with the upper and lower bound, do a binary search on the
 * solution space. This will converge to the correct answer.
 * 
 * For example, if the longest and shortest lengths are 100 and 1, start a
 * binary search at 50. Add to the flow network only edges with a length <=
 * 50. Set the capacity of each edge to 1. Check if the max flow will allow
 * the required number of trips. If yes, continue the binary search at 25. If
 * no, continue the binary search at 75.
 * 
 * As noted in the hint, the problem input is huge. Using the Java Scanner
 * class results in a TLE (Time Limit Exceeded). I've included a FasterScanner
 * class for reference.
 * 
 */
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;

class Dinic {
  private final int MAXM = 400000 + 10;
  private final int MAXN = 200 + 10;

  private int start, end;
  private int edgeCount = 0;

  private int[] head;
  private int[] vertex;
  private int[] next;
  private int[] capacity;
  private int[] flow;
  private int[] dist;
  private int[] curr;

  public Dinic() {
    head = new int[MAXN];
    Arrays.fill(head, -1);

    vertex = new int[MAXM];
    next = new int[MAXM];
    capacity = new int[MAXM];
    flow = new int[MAXM];

    dist = new int[MAXN];
    curr = new int[MAXN];
  }

  public void addEdge(int uu, int vv, int ca) {
    vertex[edgeCount] = vv;
    capacity[edgeCount] = ca;
    flow[edgeCount] = 0;
    next[edgeCount] = head[uu];
    head[uu] = edgeCount++;

    vertex[edgeCount] = uu;
    capacity[edgeCount] = 0;
    flow[edgeCount] = 0;
    next[edgeCount] = head[vv];
    head[vv] = edgeCount++;
  }

  private boolean bfs() {
    Arrays.fill(dist, -1);
    dist[start] = 0;

    Queue<Integer> qu = new LinkedList<Integer>();
    qu.add(start);

    while (!qu.isEmpty()) {
      int u = qu.poll();

      for (int e = head[u]; e != -1; e = next[e])
        if (dist[vertex[e]] == -1 && capacity[e] > flow[e]) {
          dist[vertex[e]] = dist[u] + 1;
          qu.add(vertex[e]);
        }
    }
    return dist[end] != -1;
  }

  private int dfs(int u, int a) {
    if (u == end || a == 0)
      return a;

    int f, Flow = 0;

    for (int e = curr[u]; e != -1; e = next[e]) {
      curr[u] = e;
      if (dist[vertex[e]] == dist[u] + 1
          && (f = dfs(vertex[e], Math.min(a, capacity[e] - flow[e]))) > 0) {
        flow[e] += f;
        flow[e ^ 1] -= f;
        Flow += f;
        a -= f;

        if (a == 0)
          break;
      }
    }
    return Flow;
  }

  public int maxflow(int start, int end) {
    this.start = start;
    this.end = end;

    int Flow = 0;

    while (bfs()) {
      curr = head.clone();
      Flow += dfs(start, Integer.MAX_VALUE);
    }
    return Flow;
  }
}


public class Main {

  static int N, P, T;
  static int a[], b[], w[];

  // can we flow a capacity of T through the network?
  static boolean isOk(int len) {
    Dinic din = new Dinic();

    din.addEdge(0, 1, T);

    for (int i = 0; i < P; i++) {
      if (w[i] <= len) {
        din.addEdge(a[i], b[i], 1);
        din.addEdge(b[i], a[i], 1);
      }
    }

    din.addEdge(N, N + 1, Integer.MAX_VALUE);
    return din.maxflow(0, N + 1) == T;
  }

  public static void main(String[] args) {

    FasterScanner sc = new FasterScanner(System.in);

    N = sc.nextInt();
    P = sc.nextInt();
    T = sc.nextInt();

    int L = 1000000;
    int R = 1;
    int M;

    a = new int[P];
    b = new int[P];
    w = new int[P];

    for (int i = 0; i < P; i++) {
      a[i] = sc.nextInt();
      b[i] = sc.nextInt();
      w[i] = sc.nextInt();

      if (R < w[i])
        R = w[i];
      if (L > w[i])
        L = w[i];

    }

    // binary search of solution space
    while (L <= R) {
      M = L + (R - L) / 2;

      if (isOk(M))
        R = M - 1;
      else
        L = M + 1;
    }
    System.out.println(R + 1);
  }

}

class FasterScanner {
  private InputStream mIs;
  private byte[] buf = new byte[1024];
  private int curChar;
  private int numChars;

  public FasterScanner() {
    this(System.in);
  }

  public FasterScanner(InputStream is) {
    mIs = is;
  }

  public int read() {
    if (numChars == -1)
      throw new InputMismatchException();
    if (curChar >= numChars) {
      curChar = 0;
      try {
        numChars = mIs.read(buf);
      } catch (IOException e) {
        throw new InputMismatchException();
      }
      if (numChars <= 0)
        return -1;
    }
    return buf[curChar++];
  }

  public String nextLine() {
    int c = read();
    while (isSpaceChar(c))
      c = read();
    StringBuilder res = new StringBuilder();
    do {
      res.appendCodePoint(c);
      c = read();
    } while (!isEndOfLine(c));
    return res.toString();
  }

  public String nextString() {
    int c = read();
    while (isSpaceChar(c))
      c = read();
    StringBuilder res = new StringBuilder();
    do {
      res.appendCodePoint(c);
      c = read();
    } while (!isSpaceChar(c));
    return res.toString();
  }

  public long nextLong() {
    int c = read();
    while (isSpaceChar(c))
      c = read();
    int sgn = 1;
    if (c == '-') {
      sgn = -1;
      c = read();
    }
    long res = 0;
    do {
      if (c < '0' || c > '9')
        throw new InputMismatchException();
      res *= 10;
      res += c - '0';
      c = read();
    } while (!isSpaceChar(c));
    return res * sgn;
  }

  public int nextInt() {
    int c = read();
    while (isSpaceChar(c))
      c = read();
    int sgn = 1;
    if (c == '-') {
      sgn = -1;
      c = read();
    }
    int res = 0;
    do {
      if (c < '0' || c > '9')
        throw new InputMismatchException();
      res *= 10;
      res += c - '0';
      c = read();
    } while (!isSpaceChar(c));
    return res * sgn;
  }

  public boolean isSpaceChar(int c) {
    return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
  }

  public boolean isEndOfLine(int c) {
    return c == '\n' || c == '\r' || c == -1;
  }

}

Leave a Reply

Your email address will not be published. Required fields are marked *