Cod sursa(job #2776137)

Utilizator Dragono63Stanciu Rares Stefan Dragono63 Data 18 septembrie 2021 18:21:09
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.34 kb
#include <fstream>
#include <string.h>
#include <queue>
#include <vector>
#define NMAX 1005

using namespace std;

/************************************/
/// INPUT / OUTPUT

ifstream f("maxflow.in");
ofstream g("maxflow.out");
/************************************/
/// GLOBAL DECLARATIONS

int N, M, S, D;
int maxFlow, startingNode;
int flow[NMAX][NMAX], parent[NMAX], cap[NMAX][NMAX];
vector<int> adj[NMAX];
vector<int> paths;
queue<int> q;
/************************************/
/// FUNCTIONS

void ReadInput();
void Solution();
void Output();
/************************************/
///-------------------------------------------------
inline void ReadInput()
{
    f >> N >> M;
    S = 1;
    D = N;

    for (int i = 1; i <= M; ++i)
    {
        int a, b, flux;
        f >> a >> b >> flux;

        cap[a][b] = flux;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }
}
///-------------------------------------------------
bool BFS()
{
    memset(parent, 0, sizeof(parent));
    paths.clear();
    q.push(S);

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

        for (auto u : adj[node])
        {
            if (!parent[u] && flow[node][u] < cap[node][u])
            {
                parent[u] = node;
                if (u == D)
                {
                    paths.push_back(node);
                    continue;
                }
                q.push(u);
            }
        }
    }

    return !paths.empty();
}
///-------------------------------------------------
inline void Solution()
{
    while (BFS())
    {
        for (auto start : paths)
        {
            int flux = 1e8;

            int node = D;
            parent[D] = start;

            while (node != S)
            {
                flux = min(flux, (cap[parent[node]][node] - flow[parent[node]][node]));
                node = parent[node];
            }

            maxFlow += flux;
            node = D;

            while (node != S)
            {
                int par = parent[node];
                flow[par][node] += flux;
                flow[node][par] -= flux;
                node = par;
            }
        }
    }
}
///-------------------------------------------------
inline void Output()
{
    g << maxFlow;
}
///-------------------------------------------------
int main()
{
    ReadInput();
    Solution();
    Output();
    return 0;
}