Cod sursa(job #2592976)

Utilizator Anakin1001George Giorgiu Gica Anakin1001 Data 2 aprilie 2020 17:50:42
Problema Flux maxim Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <fstream>
#include <vector>
#include <queue>

#define N 1001

using namespace std;

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

const int inf = 110001;
queue < int > q;
vector < int > graph[N];
int n, tata[N], F[N][N], C[N][N];
bool viz[N];

bool bfs ( int node ){
    for ( int i = 1; i <= n; i++ ){
        viz[i] = tata[i] = 0;
    }
    viz[1] = 1;
    q.push ( 1 );
    while ( !q.empty ( ) ){
        int node = q.front ( );
        q.pop ( );
        for ( int i = 0; i < graph[node].size ( ); i++ ){
            int new_node = graph[node][i];
            if ( viz[new_node] == 0 && F[node][new_node] < C[node][new_node] ){
                q.push ( new_node );
                tata[new_node] = node;
                viz[new_node] = 1;
            }
        }
    }
    return viz[n];
}

int main()
{   int m, i, x, y, z;
    f >> n >> m;
    for ( i = 1; i <= m; i++ ){
        f >> x >> y >> z;
        C[x][y] = z;
        graph[x].push_back ( y );
        graph[y].push_back ( x );
    }
    long long S = 0;
    while ( bfs ( 1 ) == 1 ){
        for ( int i = 0; i < graph[n].size ( ); i++ ){
            int x = graph[n][i];
            if ( C[x][n] == F[x][n] || viz[x] == 0 )
                continue;
            int Min = C[x][n] - F[x][n];
            int c = x;
            while ( x != 1 ){
                Min = min ( Min, C[tata[x]][x] - F[tata[x]][x] );
                x = tata[x];
            }
            S += 1ll * Min;
            x = c;
            while ( x != 1 ){
                F[tata[x]][x] += Min;
                F[x][tata[x]] -= Min;
                x = tata[x];
            }
        }
    }
    g << S;
    return 0;
}