Cod sursa(job #1980552)

Utilizator gabib97Gabriel Boroghina gabib97 Data 13 mai 2017 13:29:40
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>

#define N 1005
using namespace std;
int n, m, C[N][N], t[N], x, y, c, v[N], nr, flow;
vector<int> G[N];
queue<int> Q;

int BFS()
{
    int s, i;

    Q.push(1);
    while (!Q.empty()) {
        s = Q.front();
        Q.pop();

        for (i = 0; i < G[s].size(); i++)
            if (!t[G[s][i]] && C[s][G[s][i]] > 0) {
                t[G[s][i]] = s;
                Q.push(G[s][i]);
            }
    }
    return t[n];
}

int main()
{
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);

    int i;
    scanf("%i%i", &n, &m);
    for (i = 1; i <= m; i++) {
        scanf("%i%i%i", &x, &y, &c);
        G[x].push_back(y);
        G[y].push_back(x);
        if (y == n) v[++nr] = x;
        C[x][y] = c;
    }

    int w, j, x;
    while (BFS()) {
        for (j = 1; j <= nr; j++) {
            x = v[j];
            w = C[x][n];
            for (i = x; i != 1; i = t[i])
                w = min(w, C[t[i]][i]);

            for (i = x; i != 1; i = t[i]) {
                C[t[i]][i] -= w;
                C[i][t[i]] += w;
            }
            C[x][n] -= w;
            C[n][x] += w;

            flow += w;
        }
        for (i = 1; i <= n; i++) t[i] = 0;
    }
    printf("%i", flow);
    return 0;
}