Cod sursa(job #2777863)

Utilizator Dragono63Stanciu Rares Stefan Dragono63 Data 25 septembrie 2021 14:01:54
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.23 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;
int flow[NMAX][NMAX], parent[NMAX], cap[NMAX][NMAX];
vector<int> adj[NMAX];
/************************************/
/// 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);
    }
}
///-------------------------------------------------
void PushFlux()
{
    int flux = 1e8;

    int node = D;

    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;
    }
}
///-------------------------------------------------
bool BFS()
{
    bool foundPath = false;
    memset(parent, -1, sizeof(parent));
    queue<int> q;
    q.push(S);

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

        for (auto u : adj[node])
        {
            if (parent[u] == -1 && flow[node][u] < cap[node][u])
            {
                parent[u] = node;
                if (u == D)
                {
                    foundPath = true;
                    PushFlux();
                    continue;
                }
                q.push(u);
            }
        }
    }

    return foundPath;
}
///-------------------------------------------------
inline void Solution()
{
    while (BFS())
    {
        continue;
    }
}
///-------------------------------------------------
inline void Output()
{
    g << maxFlow;
}
///-------------------------------------------------
int main()
{
    ReadInput();
    Solution();
    Output();
    return 0;
}