Cod sursa(job #2022564)

Utilizator gabib97Gabriel Boroghina gabib97 Data 16 septembrie 2017 18:54:25
Problema Flux maxim Scor 100
Compilator java Status done
Runda Arhiva educationala Marime 2.21 kb
import java.util.*;
import java.io.*;

public class Main {
    static Vector<Integer>[] G;
    static int i, n, m, flow;
    static int[] T;
    static int[][] C;
    static ArrayDeque<Integer> Q = new ArrayDeque<>();

    private static boolean BFS() {
        int x;
        Q.add(1);

        while (!Q.isEmpty()) {
            x = Q.poll();

            for (int y : G[x])
                if (T[y] == 0 && C[x][y] > 0) {
                    T[y] = x;
                    Q.add(y);
                }
        }
        return T[n] != 0;
    }

    public static void main(String[] args) throws IOException {
        Scan cin = new Scan("maxflow.in");
        PrintWriter cout = new PrintWriter("maxflow.out");

        n = cin.nextInt();
        m = cin.nextInt();
        C = new int[n + 1][n + 1];
        T = new int[n + 1];
        G = new Vector[n + 1];
        for (i = 1; i <= n; i++) G[i] = new Vector<>();

        int x, y, c;
        while (m-- != 0) {
            x = cin.nextInt();
            y = cin.nextInt();
            c = cin.nextInt();
            G[x].add(y);
            G[y].add(x);
            C[x][y] = c;
        }

        int z;
        while (BFS()) {
            for (int k : G[n]) {
                z = C[k][n];

                for (i = k; i != 1; i = T[i])
                    z = Math.min(z, C[T[i]][i]);

                flow += z;

                for (i = k; i != 1; i = T[i]) {
                    C[T[i]][i] -= z;
                    C[i][T[i]] += z;
                }
                C[k][n] -= z;
                C[n][k] += z;

            }
            for (i = 1; i <= n; i++) T[i] = 0;
        }

        cout.print(flow);
        cout.close();
    }

    private static class Scan {
        BufferedReader bufferedReader;
        StringTokenizer st;

        Scan(String file) throws FileNotFoundException {
            bufferedReader = new BufferedReader(new FileReader(file));
        }

        String next() throws IOException {
            while (st == null || !st.hasMoreElements())
                st = new StringTokenizer(bufferedReader.readLine());

            return st.nextToken();
        }

        public int nextInt() throws IOException {
            return Integer.parseInt(next());
        }
    }
}