Cod sursa(job #2520521)

Utilizator LeVladzCiuperceanu Vlad LeVladz Data 9 ianuarie 2020 15:12:23
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <fstream>
#include <vector>
#include <deque>
#include <bitset>
#define INF 1000000000

using namespace std;

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

int n,m,i,j,x,y,z,cost[1005][1005],tata[1005],resid[1005][1005];
vector<int> L[1005];
deque<int> c;
bitset<1005> f;

bool bfs()
{
    f.reset(); c.push_back(1);
    f[1] = 1; tata[1] = -1;
    while (!c.empty())
    {
        int nod = c.front();
        c.pop_front();
        for (int i=0; i<L[nod].size(); i++)
        {
            int vecin = L[nod][i];
            if (!f[vecin] && resid[nod][vecin] > 0)
            {
                c.push_back(vecin);
                f[vecin] = 1; tata[vecin] = nod;
            }
        }
    }
    return f[n];
}

int main()
{
    fin >> n >> m;
    for (i=1; i<=m; i++)
    {
        fin >> x >> y >> z;
        cost[x][y] = resid[x][y] = z;
        L[x].push_back(y);
        L[y].push_back(x);
    }
    int flow = 0;
    while (bfs())
        for (i=0; i<L[n].size(); i++)
        {
            int vecin = L[n][i];
            if (f[vecin] && resid[vecin][n] > 0)
            {
                int path_flow = resid[vecin][n];
                while (vecin != 1)
                {
                    path_flow = min(path_flow, resid[tata[vecin]][vecin]);
                    vecin = tata[vecin];
                }
                vecin = L[n][i];
                resid[vecin][n] -= path_flow;
                resid[n][vecin] += path_flow;
                while (vecin != 1)
                {
                    resid[tata[vecin]][vecin] -= path_flow;
                    resid[vecin][tata[vecin]] += path_flow;
                    vecin = tata[vecin];
                }
                flow += path_flow;
            }
        }
    fout << flow;
    return 0;
}