Cod sursa(job #3041429)

Utilizator PalcPalcu Stefan Palc Data 31 martie 2023 15:05:11
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m, fluxMax;
int c[1005][1005], f[1005][1005], t[1005];
vector<int> a[1005];

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

int BFS()
{
    int x;
    queue<int> q;
    for (int i = 1; i <= n; i++)
        t[i] = 0;
    q.push(1);
    t[1] = -1;
    while (!q.empty())
    {
        x = q.front();
        q.pop();
        for (int e : a[x])
            if (t[e] == 0 && c[x][e] > f[x][e])
            {
                t[e] = x;
                q.push(e);
            }
    }
    return (t[n] != 0);
}

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

int main()
{
    Citire();
    Cineva();///nu-i mai stiu numele
    fin.close();
    fout.close();
    return 0;
}