Cod sursa(job #3036609)

Utilizator raulandreipopRaul-Andrei Pop raulandreipop Data 24 martie 2023 17:52:12
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.96 kb
#include <iostream>
#include <vector>
#include <queue>

using namespace std;
using ll = long long;
const int vmax = 1001;
const int inf = 1e9;
const int NOEDGE = 1e9 + 2;
int v, e;
int source , destination;

struct edge {
    int from , to , r;
};
vector<edge> edges;
vector<int> adjacentEdges[vmax];
int from[vmax];

bool bfs ()
{
    for (int i = 1; i <= v; i++)
    {
        from[i] = NOEDGE;
    }
    queue<int> q;
    from[source] = -1;
    q.push(source);
    while (q.size() && from[destination] == NOEDGE)
    {
        int nod = q.front();
        q.pop();
        
        for (auto &ind : adjacentEdges[nod])
        {
            int to = edges[ind].to;
            int r = edges[ind].r;
            if (r > 0 && from[to] == NOEDGE)
            {
                q.push(to);
                from[to] = ind;
            }
        }
    }
    return from[destination] != NOEDGE;
}

int main () 
{
    freopen("maxflow.in" , "r" , stdin);
    freopen("maxflow.out" , "w" , stdout);
    cin >> v >> e;
    source = 1; destination = v;
    for (int i = 1; i <= e; i++)
    {
        int x, y, c; cin >> x >> y >> c;
        adjacentEdges[x].push_back(edges.size());
        edges.push_back({x, y, c});
        adjacentEdges[y].push_back(edges.size());
        edges.push_back({y, x, 0});
    }

    ll maxFlow = 0;
    while (bfs())
    {
        int flux = inf;
        int nod = destination;
        while (nod != source)
        {
            int ind = from[nod];
            flux = min(flux , edges[ind].r);
          //  cout << nod << ' ' << edges[ind].r << '\n';
            nod = edges[ind].from;
        }
        
        nod = destination;
        while (nod != source)
        {
            int ind = from[nod];
            edges[ind].r -= flux;
            edges[ind^1].r += flux;
            nod = edges[ind].from;
        }
        
        maxFlow += flux;
    }
    cout << maxFlow << '\n';
}