Cod sursa(job #2709013)

Utilizator Marius7122FMI Ciltea Marian Marius7122 Data 19 februarie 2021 17:15:12
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.58 kb
#include <iostream>
#include <fstream>

#include <vector>
#include <queue>

class MaxFlowSolver
{
    int n, fmax;
    std::vector<int> t;
    std::vector<std::vector<int>> cap, flow, g;
    std::vector<bool> vis;

    void bfs(int startNode)
    {
        vis.assign(n + 1, false);
        std::queue<int> q;

        q.push(startNode);
        vis[startNode] = true;
        t[startNode] = 0;
        while(!q.empty())
        {
            int node = q.front();
            q.pop();

            if(node == n)
                continue;

            for(int y : g[node])
                if(cap[node][y] != flow[node][y])
                {
                    if(!vis[y])
                    {
                        vis[y] = true;
                        t[y] = node;
                        q.push(y);
                    }
                }
        }
    }

public:
    MaxFlowSolver(int _n)
    {
        n = _n;
        fmax = 0;

        cap.resize(n + 1, std::vector<int>(n + 1));
        flow.resize(n + 1, std::vector<int>(n + 1));
        g.resize(n + 1);
        t.resize(n + 1);
    }

    void addEdge(int x, int y, int c)
    {
        g[x].push_back(y);
        g[y].push_back(x);
        cap[x][y] = c;
    }

    int solve()
    {
        fmax = 0;
        do
        {
            bfs(1);

            if(vis[n] == false)
                break;
            
            for(int y : g[n])
            {
                if(vis[y] == false || cap[y][n] == flow[y][n])
                    continue;

                t[n] = y;

                int fmin = 1 << 30;
                for(int node = n; node != 1; node = t[node])
                    fmin = std::min(fmin, cap[t[node]][node] - flow[t[node]][node]);
                
                if(fmin == 0)
                    continue;

                fmax += fmin;
                for(int node = n; node != 1; node = t[node])
                {
                    flow[t[node]][node] += fmin;
                    flow[node][t[node]] -= fmin;
                }
            }
            
        } while(vis[n]);

        return fmax;
    }
};

using namespace std;

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

int n, m;

int main()
{
    fin >> n >> m;

    MaxFlowSolver maxFlowSolver(n);
    for(int i = 0; i < m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        maxFlowSolver.addEdge(x, y, c);
    }

    fout << maxFlowSolver.solve() << '\n';

    fin.close();
    fout.close();
    return 0;
}

/*



*/