Cod sursa(job #3040946)

Utilizator Tudor06MusatTudor Tudor06 Data 30 martie 2023 17:55:14
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 1e3;
const int INF = 1e9;

vector <int> edges[NMAX + 1];
int flow[NMAX + 1][NMAX + 1];
int dist[NMAX + 1];
int first_good[NMAX + 1];

int n;

bool bfs() {
    for ( int i = 1; i <= n; i ++ ) dist[i] = -1;
    dist[1] = 1;
    queue <int> q;
    q.push( 1 );
    while ( !q.empty() ) {
        int node = q.front();
        q.pop();
        for ( auto vec : edges[node] ) {
            if ( flow[node][vec] > 0 && dist[vec] == -1 ) {
                dist[vec] = dist[node] + 1;
                q.push( vec );
            }
        }
    }
    return ( dist[n] != -1 );
}
int dfs( int node, int pushed ) {
    if ( !pushed ) return 0;
    if ( node == n ) return pushed;
    for ( int& i = first_good[node]; i < edges[node].size(); i ++ ) {
        int vec = edges[node][i];
        if ( dist[vec] != dist[node] + 1 || !flow[node][vec] ) continue;
        int aux = dfs( vec, min( pushed, flow[node][vec] ) );
        if ( !aux ) continue;
        flow[node][vec] -= aux;
        flow[vec][node] += aux;
        return aux;
    }
    return 0;
}

int max_flow() {
    int total_flow = 0, aux;
    while ( bfs() ) {
        for ( int i = 1; i <= n; i ++ ) first_good[i] = 0;
        while ( ( aux = dfs( 1, INF ) ) ) total_flow += aux;
    }
    return total_flow;
}
int main() {
    ifstream fin( "maxflow.in" );
    ofstream fout( "maxflow.out" );
    int m;
    fin >> n >> m;

    for ( int i = 0, a, b, c; i < m; i ++ ) {
        fin >> a >> b >> c;
        flow[a][b] = c;
        if ( !flow[b][a] ) {
            edges[a].push_back( b );
            edges[b].push_back( a );
        }
    }

    fout << max_flow();
    return 0;
}