Cod sursa(job #2136611)

Utilizator raul044Moldovan Raul raul044 Data 20 februarie 2018 00:45:25
Problema Flux maxim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2.07 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define maxN 1000

using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

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

int n, m, S, D, tata[maxN] , flux[maxN][maxN], cost[maxN][maxN], F, v[maxN];
bool drum;

void citire () {
    fin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y, c;
        fin >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
        fin >> cost[x][y];
    }
    fin.close();
}

void initializare () {
    for (int i = 1; i <= n; i++) {
        tata[i] = 0;
    }
}

bool bfs () {
    bool ok = false;
    initializare();
    tata[S] = -1;
    Q.push(S);
    while (!Q.empty()) {
        int x = Q.front();
        int size = G[x].size();
        for (int i = 0; i < size; ++i) {
            int y = G[x][i];
            if (tata[y] == 0 and cost[x][y] > flux[x][y]) {
                if (y != D) {
                    Q.push(y);
                    tata[y] = x;
                }
                else {
                    ok = true;
                }
            }
        }
        Q.pop();
    }
    return ok;
}

void dinitz () {
    drum = bfs(); /// 0 sau 1 daca ajunge in D
    while (drum) {
        int size = G[D].size();
        for (int i = 0; i < size; ++i) {


            int u = G[D][i];
            if (tata[u] and cost[u][D] > flux[u][D]) {
                int min = 110000;
                tata[D] = u;

                for (int nod = D; nod != S; nod = tata[nod]) {
                    if (min > cost[tata[nod]][nod] - flux[tata[nod]][nod])
                        min = cost[tata[nod]][nod] - flux[tata[nod]][nod];
                }
                if (min <= 0) continue;

                F += min;
                for (int nod = D; nod != S; nod = tata[nod]) {
                    flux[tata[nod]][nod] += min;
                }
            }

        }
        drum = bfs();
    }
}

int main () {
    citire();
    S = 1; D = n;
    dinitz();
    fout << F;
}