Cod sursa(job #2989726)

Utilizator Vlad.Vlad Cristian Vlad. Data 6 martie 2023 22:23:46
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <fstream>
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>

#define NMAX 1005
#define INF 999999999

using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

int cap[NMAX][NMAX], fl[NMAX][NMAX];
bool d[NMAX];
int t[NMAX];
int N, M;
vector<vector<int>> gr;

void read() {
    fin >> N >> M;
    gr.resize(N + 1);
    int x, y, cp;
    for (int i = 1; i <= M; ++i) {
        fin >> x >> y >> cp;
        cap[x][y] = cp;
        gr[x].push_back(y);
        gr[y].push_back(x);
    }
}

bool bfs(int st) {
    int node;
    queue<int> q;
    q.push(st);
    d[st] = true;
    while (!q.empty()) {
        node = q.front();
        q.pop();
        if (node != N) {
            for (int v : gr[node]) {
                if (d[v] == false && fl[node][v] < cap[node][v])  {
                    q.push(v);
                    d[v] = true;
                    t[v] = node;
                }
            }
        }
    }
    return d[N];
}

int main()
{

    read();

    int flow;
    while (bfs(1)) {
        for (int v : gr[N]) {
            if (d[v] && fl[v][N] < cap[v][N]) {
                flow = INF;
                for (int i = N; i != 1; i = t[i]) {
                    flow = min(flow, cap[t[i]][i] - fl[t[i]][i]);
                }
                for (int i = N; i != 1; i = t[i]) {
                    fl[t[i]][i] += flow;
                    fl[i][t[i]] -= flow;
                }
            }
        }
        memset(d, 0, sizeof d);
        memset(t, 0, sizeof t);
    }

    int total = 0;
    for (int v : gr[N]) {
        total += fl[v][N];
    }
    fout << total << "\n";

    return 0;
}