Cod sursa(job #2579560)

Utilizator cristina-criCristina cristina-cri Data 12 martie 2020 16:43:07
Problema Flux maxim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 1005
#define INF 0x3f3f3f3f
using namespace std;

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

vector <int>graph[NMAX];
queue <int>q;

int n, m, x, y, capacitate;
int c[NMAX][NMAX];
int flow;
int f[NMAX][NMAX];
int viz[NMAX];
int tata[NMAX];

void zero()
{
    for(int i=1; i<=n; i++)
        viz[i]=0;
}

int bfs()
{
    q.push(1);
    zero();
    viz[1]=1;
    while(!q.empty())
    {
        int vf=q.front();
        q.pop();
        if(vf == n)
            continue;
        for(auto &v:graph[vf])
        {
            if(c[vf][v] == f[vf][v] || viz[v])
                continue;
            viz[v]=1;
            q.push(v);
            tata[v]=vf;
        }
    }
    return viz[n];
}

int flowToAdd;

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

    for(int i=1; i<=m; i++)
    {
        fin>>x>>y>>capacitate;
        graph[x].push_back(y);
        graph[y].push_back(x);
        c[x][y]=capacitate;
    }

    for(flow=0; bfs();)
    {
        for(auto &v:graph[n])
        {
            if(c[v][n] == f[v][n] || !viz[v])
                continue;
            tata[n]=v;

            flowToAdd=INF;
            for(int vf=n; vf!=1; vf=tata[vf])
                flowToAdd=min(flowToAdd, c[tata[vf]][vf]-f[tata[vf]][vf]);
            if(flowToAdd == 0)
                continue;
            for(int vf=n; vf!=1; vf=tata[vf])
            {
                f[tata[vf]][vf]+=flowToAdd;
                //f[vf][tata[vf]]-=flowToAdd;
            }
            flow+=flowToAdd;
        }
    }
    g<<flow;

    return 0;
}