Cod sursa(job #2960433)

Utilizator lucianul31Moisii Lucian lucianul31 Data 4 ianuarie 2023 13:33:56
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.67 kb
// O(N*M^2)
#include <iostream>
#include <fstream>
#include <string.h>
#include <queue>

using namespace std;

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

const int NMAX = 5005;
int N, M, Graph[NMAX][NMAX], Father[NMAX], Total_Flow;
bool Seen[NMAX];
vector < int > Edges[NMAX];
queue < int > Q;

int BFS()
{
    int X, Flow = 0, bottleneck;
    memset(Seen, 0, sizeof(int) * (N + 5));
    Q.push(1);
    Seen[1] = 1;
    while(!Q.empty())
    {
        X = Q.front();
        Q.pop();
        for(int newX : Edges[X])
        {
            if(newX == N)
                continue;
            if(!Seen[newX] && Graph[X][newX] > 0)
                Q.push(newX), Seen[newX] = 1, Father[newX] = X;
        }
    }
    for(int Node : Edges[N])
    {
        if(!Seen[Node])
            continue;
        X = Node;
        bottleneck = Graph[X][N];
        while(Father[X])
        {
            bottleneck = min(Graph[Father[X]][X], bottleneck);
            X = Father[X];
        }
        Flow += bottleneck;
        X = Node;
        Graph[N][X] += bottleneck;
        Graph[X][N] -= bottleneck;
        while(Father[X])
        {
            Graph[X][Father[X]] += bottleneck;
            Graph[Father[X]][X] -= bottleneck;
            X = Father[X];
        }
    }
    return Flow;
}

int main()
{
    int x, y, c;
    in >> N >> M;
    for(int i = 1; i <= M; i++)
    {
        in >> x >> y >> c;
        Edges[x].push_back(y);
        Edges[y].push_back(x);
        Graph[x][y] = c;
    }
    c = BFS();
    while (c)
    {
        Total_Flow += c;
        c = BFS();
    }
    out << Total_Flow;
    return 0;
}