Cod sursa(job #2959373)

Utilizator selenahurloiSelena Hurloi selenahurloi Data 30 decembrie 2022 21:19:35
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <iostream>
#include <fstream>
#include <climits>
#include <vector>
#include <queue>

using namespace std;

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

int N, M, s, f;
vector<int> tata;
vector<vector<int>> capacitate;
vector<vector<int>> LA;
bool bfs()
{
    vector<bool> viz(N+1);
    queue<int> q;
    q.push(s);
    viz[s] = true;
    tata[s] = -1;
    while(!q.empty())
    {
        int u = q.front();
        q.pop();
        for(auto v: LA[u])
        {
            if(viz[v]==false && capacitate[u][v]!=0)
            {
                tata[v] = u;
                if(v == f)
                    return true;
                viz[v] = true;
                q.push(v);
            }
        }
    }
    return false;
}

int EdmondsKarp()
{
    long max_flow = 0;
    while(bfs())
    {
        int u, v, path_flow = INT_MAX;
        for(v = f; v != s; v = tata[v])
        {
            u = tata[v];
            if(capacitate[u][v] < path_flow)
                path_flow = capacitate[u][v];
        }
        for(v = f; v != s; v = tata[v])
        {
            u = tata[v];
            capacitate[u][v] -= path_flow;
            capacitate[v][u] += path_flow;
        }
        max_flow += path_flow;
    }
    return max_flow;
}

int main()
{
    fin >> N >> M;
    s = 1;
    f = N;
    LA.resize(N+1);
    tata.resize(N+1);
    capacitate.resize(N+1, vector<int>(N+1));
    for(int i = 1; i <= M; i++)
    {
        int u, v;
        long c;
        fin >> u >> v >> c;
        LA[u].push_back(v);
        LA[v].push_back(u);
        capacitate[u][v] = c;
    }
    fout << EdmondsKarp();
    return 0;
}