Cod sursa(job #3320319)

Utilizator stanciuvalentinStanciu-Tivlea Valentin Gabriel stanciuvalentin Data 4 noiembrie 2025 22:10:03
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("maxflow.in");
ofstream g("maxflow.out");

int n,m, cap[1020][1020], flow[1020][1020], dist[1020];
vector <int> edges[1020];
queue <int> q;

bool bfs(int source, int sink){
    for(int i=1; i<=n; i++)
        dist[i] = INT_MAX;
    dist[source] = 0;
    q.push(source);
    while(!q.empty())
    {
        int x = q.front();
        q.pop();
        for(auto y:edges[x])
            if(dist[y] > dist[x]+1 and flow[x][y] < cap[x][y])
                dist[y] = dist[x]+1, q.push(y);
    }
    return dist[sink]!=INT_MAX;
}

int maxflow(int x, int sink, int maximumflow){
    if(maximumflow == 0)
        return 0;
    if(x == sink)
        return maximumflow;
    int totalflow = 0;
    for(auto y:edges[x])
        if(dist[y] == dist[x]+1)
        {
            int currentflow = maxflow(y, sink, min(maximumflow - totalflow, cap[x][y] - flow[x][y]));
            flow[x][y] += currentflow;
            flow[y][x] -= currentflow;
            totalflow += currentflow;
        }
    return totalflow;
}

int x,y,z;

int main()
{
    f>>n>>m;
    for(int i=1; i<=m; i++)
    {
        f>>x>>y>>z;
        cap[x][y]+=z;
        edges[x].push_back(y);
        edges[y].push_back(x);
    }
    int totalflow = 0;
    while( bfs(1,n) )
        totalflow += maxflow(1, n, INT_MAX);
    g<<totalflow;
    return 0;
}