Cod sursa(job #2380967)

Utilizator SahMatCodrea Andrei SahMat Data 15 martie 2019 18:57:40
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <cstdio>
#include <cstring>
#include <vector>

using namespace std;

#define NMAX 1024
#define INF 0x60000000

int C[NMAX][NMAX];
int F[NMAX][NMAX];
int p[NMAX];
vector<int> G[NMAX]; // listele vecinilor
int N, M;
int c[NMAX];
int viz[NMAX];

bool BF() {
    int i, j, nod, V, l;

    l = 1; c[1] = 1;
    memset(viz, 0, sizeof(viz));
    viz[1] = 1;
    for (i = 1; i <= l; i++) {
        nod = c[i];
        for (j = 0; j < G[nod].size(); j++) { // pentru fiecare vecin al nodului
            V = G[nod][j];
            if (C[nod][V] != F[nod][V] and !viz[V]) { // Trimitem flux pe (nod,V).
                viz[V] = 1; l++; c[l] = V; p[V] = nod;
                if (V == N)
                    return true;
            }
        }
    }
    return false;
}

int main()
{
    int i, flow, fmin, x, y, z, nod;

    freopen("maxflow.in", "r", stdin);  freopen("maxflow.out", "w", stdout);
    scanf("%d %d ", &N, &M);
    for (i = 1; i <= M; i++) {
        scanf("%d %d %d ", &x, &y, &z);
        C[x][y] = z;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    for (flow = 0; BF(); flow += fmin) {
        fmin = INF;
        for (nod = N; nod != 1; nod = p[nod]) {
            fmin = min (fmin, C[p[nod]][nod] - F[p[nod]][nod]);
        }
        for (nod = N; nod != 1; nod = p[nod]) {
            F[p[nod]][nod] += fmin;
            F[nod][p[nod]] -= fmin;
        }
    }
    printf("%d ", flow);
    return 0;
}