Cod sursa(job #2810738)

Utilizator OrzataAndreiOrzata Andrei OrzataAndrei Data 30 noiembrie 2021 08:45:47
Problema Flux maxim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.2 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");

const int MAXN = 1005;

int c[MAXN][MAXN], f[MAXN][MAXN], h[MAXN],visited[MAXN];
vector<int> edges[MAXN], edges_reverse[MAXN];

int n,m,source,sink,flow;

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

    memset(visited,0,sizeof(visited));
    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;

}

void maxflow()
{
    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]);

                if (fmin == 0)
                    continue;

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

                }
                flow+=fmin;
            }

    }

}
int main()
{

    in>>n>>m;
    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;

    }
    maxflow();
    out<<flow;

    return 0;

}