Cod sursa(job #1971319)

Utilizator Andrei1998Andrei Constantinescu Andrei1998 Data 20 aprilie 2017 11:24:52
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include <fstream>
#include <algorithm>
#include <queue>

//11:15
using namespace std;

const int NMAX = 1000 + 5;
const int MMAX = 5000 + 5;

int cap[NMAX][NMAX];
vector <int> graph[NMAX];

int N;
int S = 1;
int T;

bool vis[NMAX];
int father[NMAX];
queue <int> q;

bool bfs() {
    for (int i = 1; i <= N; ++ i)
        vis[i] = father[i] = 0;
    q.push(S);
    vis[S] = true;

    int node;
    while (!q.empty()) {
        node = q.front();
        q.pop();

        for (auto it: graph[node])
            if (!vis[it] && cap[node][it]) {
                vis[it] = true;
                q.push(it);
                father[it] = node;
            }
    }

    return vis[T];
}

int maxflow() {
    int f = 0;
    while (bfs()) {
        for (int i = 1; i <= N; ++ i)
            if (vis[i] && cap[i][T]) {
                int node = i;
                int c = cap[node][T];
                while (father[node]) {
                    c = min(c, cap[father[node]][node]);
                    node = father[node];
                }

                f += c;
                cap[i][T] -= c;
                cap[T][i] += c;

                node = i;
                while (father[node]) {
                    cap[father[node]][node] -= c;
                    cap[node][father[node]] += c;
                    node = father[node];
                }
            }
    }

    return f;
}

int main()
{
    ifstream cin("maxflow.in");
    ofstream cout("maxflow.out");

    int M = 0;
    cin >> N >> M;
    T = N;

    for (int i = 1; i <= M; ++ i) {
        int a, b, c;
        cin >> a >> b >> c;
        cap[a][b] += c;
        graph[a].push_back(b);
        graph[b].push_back(a);
    }

    cout << maxflow() << '\n';
    return 0;
}