Cod sursa(job #2393802)

Utilizator andrei32576Andrei Florea andrei32576 Data 1 aprilie 2019 08:48:38
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <bits/stdc++.h>
using namespace std;

#define nmax 1005
#define inf 2000000000

int n, m, i, x, y, z, flow, fm;
int c[nmax][nmax], F[1005][1005], t[1005], viz[1005];
vector <int> G[1005];
queue <int> q;

ifstream f("maxflow.in");
ofstream g("maxflow.out");

int bfs()
{
    while (!q.empty())
        q.pop();
    q.push(1);

    memset(viz, 0, sizeof(viz));

    while (!q.empty())
    {
        int nod = q.front();
        q.pop();
        if (nod == n)
            continue;
        for (auto &it : G[nod])
        {
            if (!viz[it] && !(c[nod][it] == F[nod][it]))
            {
                viz[it] = 1;
                q.push(it);
                t[it] = nod;
            }
        }
    }

    return viz[n];
}

int main()
{
    f>>n>>m;

    for (i=1;i<=m;i++)
    {
        f>>x>>y>>z;
        c[x][y] = z;
        G[x].push_back(y);
        G[y].push_back(x);
    }

    flow = 0;
    while (bfs())
    {
        for (auto &it : G[n])
        {
            if(c[it][n] == F[it][n] || !viz[it])
                continue;
            t[n] = it;

            fm = inf;
            for (int nod = n; nod != 1; nod = t[nod])
                fm = min(fm, c[t[nod]][nod] - F[t[nod]][nod]);

            for (int nod = n; nod != 1; nod = t[nod])
            {
                F[t[nod]][nod] += fm;
                F[nod][t[nod]] -= fm;
            }

            flow += fm;
        }
    }

    g<<flow;

    f.close();
    g.close();
    return 0;
}