Cod sursa(job #2889882)

Utilizator AlexNicuNicu Alexandru AlexNicu Data 13 aprilie 2022 18:00:50
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

#define NMAX 1005

vector<int> G[NMAX];
int capacitate[NMAX][NMAX];
int parent[NMAX];

#define INF (1 << 30)
int n;

int bfs ( int source, int destination ) {
    int cur, flow;
    fill( parent, parent + n + 1, 0 );
    parent[source] = -1;
    queue<pair<int, int>> q;
    q.push({source, INF});
    while ( !q.empty() ) {
        cur = q.front().first;
        flow = q.front().second;
        q.pop();
        for ( auto copil : G[cur] ) {
            if ( parent[copil] == 0 && capacitate[cur][copil] ) {
                parent[copil] = cur;
                int min_flow = min ( flow, capacitate[cur][copil] );
                if ( copil == destination ) {
                    return min_flow;
                }
                q.push({copil, min_flow});
            }
        }
    }
    return 0;
}

int max_flow ( int source, int destination ) {
    int flow, new_flow, cur, prev;
    flow = 0;
    new_flow = 1;
    while ( new_flow ) {
        new_flow = bfs( source, destination );
        if ( new_flow ) {
            flow += new_flow;
            cur = destination;
            while (cur != source) {
                prev = parent[cur];
                capacitate[prev][cur] -= new_flow;
                capacitate[cur][prev] += new_flow;
                cur = prev;
            }
        }
    }
    return flow;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int m, i, x, y, c;
    cin >> n >> m;
    for ( i = 1; i <= m; i++ ) {
        cin >> x >> y >> c;
        G[x].push_back(y);
        G[y].push_back(x);
        capacitate[x][y] = c;
    }
    cout << max_flow(1, n) << "\n";
    return 0;
}