Cod sursa(job #1317843)

Utilizator pop_bogdanBogdan Pop pop_bogdan Data 15 ianuarie 2015 11:42:02
Problema Flux maxim Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;

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

#define maxN 1002

int N, M, x, y, z, T[maxN], C[maxN][maxN], F[maxN][maxN], Sol;
bool B[maxN];

vector <int> G[maxN];
queue <int> Q;

void Input();
bool BFS();
void EdmondKarps();

int main()
{
    Input();
    EdmondKarps();

    os << Sol;

    is.close();
    os.close();
}

void Input()
{
    is >> N >> M;
    for ( int i = 1; i <= M; ++i )
    {
        is >> x >> y >> z;
        G[x].push_back(y);
        G[y].push_back(x);
        C[x][y] = z;
    }
}

bool BFS()
{
    int node;
    memset(B,0,sizeof(B));
    B[1] = true;

    Q.push(1);
    while ( !Q.empty() )
    {
        node = Q.front();
        Q.pop();
        for ( const auto& v : G[node] )
        {
            if ( !B[v] && C[node][v] - F[node][v] > 0 )
            {
                T[v] = node;
                B[v] = 1;
                Q.push(v);
            }
        }
    }
    if ( B[N] )
        return 1;
    else
        return 0;
}

void EdmondKarps()
{
    int minim;
    while ( BFS() )
    {
        for ( const auto& v : G[N] )
        {
            minim = 0x3f3f3f3f;
            if ( F[v][N] == C[v][N] || B[v] == 0 )
                continue;
            T[N] = v;

            for ( int i = N; i != 1; i = T[i] )
                minim = min(minim,C[T[i]][i] - F[T[i]][i]);

            if (minim == 0 ) continue;

            for ( int i = N; i != 1; i = T[i] )
            {
                F[T[i]][i] += minim;
                F[i][T[i]] -= minim;
            }

            Sol += minim;
        }
    }
}