Cod sursa(job #2990729)

Utilizator Latyn76Tinica Alexandru Stefan Latyn76 Data 8 martie 2023 13:48:18
Problema Flux maxim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <bits/stdc++.h>
using namespace std;

/**
0 0 1 0
1 0 1 0
0 0 0 0
0 1 1 0

*/
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int c[1002][1002], f[1002][1002], n, m;
vector<int> L[1002];
int S, D, t[1002], fluxMax;
/// t[i] = predecesorul nodului i din drumul
///      de la S la i

/// ret. daca ajungem in D
int BFS()
{
    int k, i;
    queue<int> q;
    for (i = 1; i <= n; i++)
        t[i] = 0;
    q.push(S);
    t[S] = -1;
    while (!q.empty())
    {
        k = q.front();
        q.pop();
        for (int i : L[k])
            if (t[i] == 0 && c[k][i] > f[k][i])
            {
                t[i] = k;
                q.push(i);
            }
    }
    return (t[D] != 0);
}

void Dinic()
{
    int i, j, r;
    fluxMax = 0;
    while (BFS() != 0)
    {
        for (i = 1; i <= n; i++)
            if (i != S && i != D && c[i][D]>f[i][D])
            {
                r = c[i][D] - f[i][D];
                j = i;
                while (j != S)
                {
                    r = min(r, c[t[j]][j]-f[t[j]][j]);
                    j = t[j];
                }
                if (r == 0) continue;
                fluxMax += r;
                f[i][D] += r;
                f[D][i] -= r;
                j = i;
                while (j != S)
                {
                    f[t[j]][j] += r;
                    f[j][t[j]] -= r;
                    j = t[j];
                }
            }
    }
    fout << fluxMax << "\n";
}

int main()
{
    int i, x, y, cost;
    fin >> n >> m;
    for (i = 1; i <= m; i++)
    {
        fin >> x >> y >> cost;
        c[x][y] = cost;
        L[x].push_back(y);
    }
    S = 1; D = n;
    Dinic();
    fout.close();
    return 0;
}