Cod sursa(job #3260335)

Utilizator yolomodDamian Alexandru yolomod Data 1 decembrie 2024 18:43:40
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
const int INF = 1e9;
const int nmax = 1005;
int n, m;
vector<vector<int>> graf(nmax), rezidual(nmax, vector<int>(nmax, 0));
vector<int> parent(nmax);
int bfs(int s, int t)
{
    fill(parent.begin(), parent.end(), -1);
    parent[s] = -2;
    queue<pair<int, int>> q;
    q.push({s, INF});

    while(!q.empty())
    {
        auto [current, flow] = q.front();
        q.pop();

        for(int neighbor : graf[current])
        {
            if(parent[neighbor] == -1 && rezidual[current][neighbor])
            {
                parent[neighbor] = current;
                int new_flow = min(flow, rezidual[current][neighbor]);
                if (neighbor == t)
                    return new_flow;
                q.push({neighbor, new_flow});
            }
        }
    }
    return 0;
}

int maxflow(int s, int t)
{
    int flow=0;
    int new_flow;
    while(new_flow = bfs(s, t))
    {
        flow+=new_flow;
        int current = t;
        while(current!=s)
        {
            int previous = parent[current];
            rezidual[previous][current]-=new_flow;
            rezidual[current][previous]+=new_flow;
            current = previous;
        }
    }
    return flow;
}
int main()
{
    in>>n>>m;
    for(int i=0;i<m;i++)
    {
        int a, b, c;
        in>>a>>b>>c;
        graf[a].emplace_back(b);
        graf[b].emplace_back(a);
        rezidual[a][b] = c;
    }
    int maxFlow = maxflow(1, n);
    out<<maxFlow;
    return 0;
}