Cod sursa(job #2734722)

Utilizator Tudor_PascaTudor Pasca Tudor_Pasca Data 1 aprilie 2021 12:09:57
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

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

const int INF = 0x3f3f3f3f3f3f3f3f;

int n, m, maxFlow;
int cap[1010][1010], flow[1010][1010], father[1010];
bool fr[1010];
vector<vector<int>> adj;

bool bfs()
{
    queue<int> q;
    q.push(1);

    memset(fr, 0, sizeof fr);
    fr[1] = 1;

    memset(father, INF, sizeof father);
    father[1] = -1;

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

        if(node == n)
            continue;

        for(auto it: adj[node])
        {
            if(fr[it] == 0 && (cap[node][it] - flow[node][it] > 0))
            {
                father[it] = node;
                fr[it] = 1;
                q.push(it);
            }
        }
    }

    return fr[n];
}

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

    adj.resize(n + 5);

    for(int i = 1; i <= m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;

        adj[x].push_back(y);
        adj[y].push_back(x);

        cap[x][y] = c;
    }

    while(bfs())
    {
        for(auto node: adj[n])
        {
            if(fr[node] == 1 && flow[node][n] < cap[node][n])
            {
                node = father[n];
                int bottleNeck = INF;

                for(int i = n; i != -1; i = father[i])
                    bottleNeck = min(bottleNeck, cap[father[i]][i] - flow[father[i]][i]);

                for(int i = n; i != -1; i = father[i])
                {
                    flow[father[i]][i] += bottleNeck;
                    flow[i][father[i]] -= bottleNeck;
                }

                maxFlow += bottleNeck;
            }
        }
    }

    out << maxFlow << '\n';

    return 0;
}