Cod sursa(job #1800265)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 7 noiembrie 2016 17:04:21
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.44 kb
#include <cstdio>
#include <cstring>

using namespace std;

#define MaxN 1000
#define MaxM 5000
#define NIL -1

struct Network {
    struct Edge {
        int v, cap;
        int next;
    } G[2 * MaxM];

    int head[MaxN];
    int N;
    int edgePtr;

    void SetSize(const int numNodes) {
        memset(head, NIL, 4 * numNodes);
        N = numNodes;
        edgePtr = 0;
    }

    void AddEdge(const int u, const int v, const int cap) {
        G[edgePtr].v = v;
        G[edgePtr].cap = cap;
        G[edgePtr].next = head[u];
        head[u] = edgePtr++;
    }

    int dist[MaxN];
    int Q[MaxN];

    bool BFS() {
        int qHead = 0, qTail = 1;
        memset(dist, 0, 4 * N);
        Q[0] = 0;
        dist[0] = 1;
        while ((qHead != qTail) && (!dist[N - 1])) {
            const int node = Q[qHead++];
            for (int i = head[node]; i != NIL; i = G[i].next) {
                const int son = G[i].v;
                if (G[i].cap > 0 && !dist[son]) {
                    dist[son] = dist[node] + 1;
                    Q[qTail++] = son;
                }
            }
        }
        return dist[N - 1];
    }

    int to[MaxN];

    int DFS(const int node, const int flow) {
        if (node == N - 1) {
            return flow;
        }
        for (; to[node] != NIL; to[node] = G[to[node]].next) {
            if ((G[to[node]].cap > 0) && (dist[G[to[node]].v] == dist[node] + 1)) {
                const int pushFlow = (flow < G[to[node]].cap ? flow : G[to[node]].cap);
                const int pushed = DFS(G[to[node]].v, pushFlow);
                if (pushed) {
                    G[to[node]].cap -= pushed;
                    G[to[node] ^ 1].cap += pushed;
                    return pushed;
                }
            }
        }
        return 0;
    }

    int MaxFlow() {
        int flow = 0;
        while (BFS()) {
            memmove(to, head, 4 * N);
            int pushed;
            do {
                pushed = DFS(0, 0x3f3f3f3f);
                flow += pushed;
            } while (pushed);
        }
        return flow;
    }

} Dinic;

int main() {
    freopen("maxflow.in", "rb", stdin);
    freopen("maxflow.out", "wb", stdout);

    int N, M;
    scanf("%d %d", &N, &M);
    Dinic.SetSize(N);
    for (int i = 0; i < M; i++) {
        int u, v, cap;
        scanf("%d %d %d", &u, &v, &cap);
        Dinic.AddEdge(u - 1, v - 1, cap);
        Dinic.AddEdge(v - 1, u - 1, 0);
    }
    printf("%d\n", Dinic.MaxFlow());
    return 0;
}