Cod sursa(job #2696287)

Utilizator paulconst1Constantinescu Paul paulconst1 Data 15 ianuarie 2021 17:40:52
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 kb
#include<bits/stdc++.h>

using namespace std;

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

#define N 1001
#define fi first
#define se second
#define INF 100001

int adj[N][N];
int n,m;
vector<int> path(N, 0);
vector<int> v[N];

void bfs()
{
    queue<int> q;
    for(int i = 1; i <= n; i++)
    {
        path[i] = 0;
    }
    q.push(1);
    path[1] = -1;
    while(!q.empty() && !path[n])
    {
        int curr = q.front();
        q.pop();
        for(auto j: v[curr])
        {
            if(adj[curr][j])
            {
                if(!path[j])
                {
                    path[j] = curr;
                    q.push(j);
                }
            }
        }
    }
}

int maxflow()
{
    int ans = 0;
    while(true)
    {
        bfs();
        if(path[n] == 0)
            return ans;
        else
        {
            for(auto pred: v[n])
            {
                int curr = n;
                path[n] = pred;
                if(path[pred] > 0)
                {
                    int flow = INF;
                    while(path[curr] != -1)
                    {
                        flow = min(flow, adj[path[curr]][curr]);
                        curr = path[curr];
                    }
                    curr = n;
                    while(path[curr] != -1)
                    {
                        adj[path[curr]][curr] -= flow;
                        adj[curr][path[curr]] += flow;
                        curr = path[curr];
                    }
                    ans += flow;
                }

            }
        }

    }
}


int main()
{

    fin>>n>>m;
    for(int i = 0; i<m; i++)
    {
        int a,b,c;
        fin>>a>>b>>c;
        adj[a][b] = c;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    fout<<maxflow();

    return 0;
}