Cod sursa(job #2695613)

Utilizator anacomoAna-Maria Comorasu anacomo Data 13 ianuarie 2021 22:08:49
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>
#define NMAX 1001
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int inf = 1e9;

int n, rez[NMAX][NMAX], prv[NMAX];
vector<int> graph[NMAX];
queue<int> qu;
bool visited[NMAX];

bool Bfs(int s, int d)
{
    for (int i = 1; i <= n; ++i)
        visited[i] = 0;
    visited[s] = 1;
    qu.push(s);
    while (!qu.empty())
    {
        int node = qu.front();
        qu.pop();
        for (auto i : graph[node])
        {
            if (visited[i] || !rez[node][i])
                continue;
            visited[i] = 1;
            prv[i] = node;
            if (i != d)
                qu.push(i);
        }
    }
    return visited[d];
}

int main()
{
    int m;
    fin >> n >> m;
    for (int i = 1, x, y, c; i <= m; ++i)
    {
        fin >> x >> y >> c;
        graph[x].push_back(y);
        graph[y].push_back(x);
        rez[x][y] = c;
    }

    int maxFlow = 0;
    while (Bfs(1, n))
    {
        for (auto i : graph[n])
        {
            if (!visited[i] || !rez[i][n])
                continue;
            int aux = inf;
            prv[n] = i;
            for (int node = n; node != 1; node = prv[node])
                aux = min(aux, rez[prv[node]][node]);
            for (int node = n; node != 1; node = prv[node])
            {
                rez[prv[node]][node] -= aux;
                rez[node][prv[node]] += aux;
            }
            maxFlow += aux;
        }
    }
    fout << maxFlow;
    fin.close();
    fout.close();
    return 0;
}