Cod sursa(job #2810735)

Utilizator OrzataAndreiOrzata Andrei OrzataAndrei Data 30 noiembrie 2021 08:29:16
Problema Flux maxim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.14 kb
#include <iostream>
#include <fstream>
#include <string.h>
#include <climits>
#include <vector>
#include <queue>

using namespace std;

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




int N,M,source,sink,flow;
int h[1001],visited[1001],c[1001][1001], f[1001][1001];

bool BFS(vector<int>edges[],vector<int> edges_reverse[] )
{


    for(int i=1; i<=N; i++)
    {
        h[i]=0;
        visited[i]=0;
    }
    queue<int> Q;
    Q.push(sink);
    visited[sink]=1;

    while(!Q.empty())
    {
        int x = Q.front();
        Q.pop();

        for(auto y :edges[x])
        {

            if(visited[y]==0&&c[x][y]-f[x][y]>0)
            {
                Q.push(y);
                h[y] = x;
                visited[y] = 1;

                if(y==source)
                    return true;

            }

        }

        for(auto y : edges_reverse[x])
        {
            if(visited[y]==0&&f[y][x]>0)
            {
                Q.push(y);
                h[y] = -x;
                visited[y] = 1;

                if(y==source)
                    return true;

            }

        }

    }
    return false;

}


int main()
{

    in>>N>>M;
    vector<int> edges[N], edges_reverse[N];

    for(int i=1; i<=M; i++)
    {
        int x,y,z;

        in>>x>>y>>z;
        edges[x].push_back(y);
        edges_reverse[y].push_back(x);
        c[x][y]=z;
        f[x][y]=0;
    }

    sink=1;
    source=N;

    while(BFS(edges,edges_reverse))
    {

        for(auto node : edges_reverse[source])
            if(f[node][source] != c[node][source] && visited[node])
            {
                h[source] = node;
                int fmin=INT_MAX;

                for(int nod = source; nod!= sink; nod = h[nod])
                    fmin=min(fmin, c[h[nod]][nod]-f[h[nod]][nod]);

                for(int nod = source; nod!=sink; nod = h[nod])
                {
                    f[nod][h[nod]]-=fmin;
                    f[h[nod]][nod]+=fmin;

                }
                flow+=fmin;
            }
    }


    out<<flow;

    return 0;
}