Cod sursa(job #2485856)

Utilizator alexsandulescuSandulescu Alexandru alexsandulescu Data 2 noiembrie 2019 10:10:12
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("maxflow.in");
ofstream g("maxflow.out");

int N, M, x, y, c;
int C[1003][1003], F[1003][1003], T[1003];
vector<int> G[1003];

bool BFS(int S, int D) {
    for(int i = 1; i <= N; i++)
        T[i] = -1;
    T[S] = 0;
    queue<int> Q; Q.push(S);
    while(!Q.empty()) {
        int Node = Q.front(); Q.pop();
        for(auto it : G[Node])
        if(T[it] == -1 && C[Node][it] != F[Node][it]) {
            T[it] = Node;
            if(it == D) return 1;
            Q.push(it);
        }
    }
    return 0;
}
int MaxFlow(int S, int D) {
    int flux = 0;
    while(BFS(S, D)) {
        for(auto it : G[D])
        if(T[it] != -1) {
            int add = C[it][D] - F[it][D];
            int Node = it, dad = 0;
            while(Node != S) {
                dad = T[Node];
                add = min(add, C[dad][Node] - F[dad][Node]);
                Node = dad;
            }
            F[it][D] += add;
            F[D][it] -= add;
            flux += add;
            Node = it;
            while(Node != S) {
                dad = T[Node];
                F[dad][Node] += add;
                F[Node][dad] -= add;
                Node = dad;
            }
        }
    }
    return flux;
}
int main()
{
    f >> N >> M;
    for(int i = 1; i <= M; i++) {
        f >> x >> y >> c;
        C[x][y] = c;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    g << MaxFlow(1, N) << "\n";
    return 0;
}