Cod sursa(job #3359978)

Utilizator Cristian_NegoitaCristian Negoita Cristian_Negoita Data 7 iulie 2026 12:55:11
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int NMAX = 1001, INF = 1e9;
int n, m, cap[NMAX][NMAX], parent[NMAX];
vector<int> adj[NMAX];

bool bfs(int source, int dest)
{
    memset(parent, 0, sizeof(parent));
    queue<int> Q({source});
    parent[source] = -1;
    while(!Q.empty())
    {
        int node = Q.front(); Q.pop();
        for(int next : adj[node])
        {
            if(parent[next] == 0 && cap[node][next] > 0)
            {
                parent[next] = node;
                if(next == dest)
                    return true;
                Q.push(next);
            }
        }
    }
    return false;
}

int maxflow(int source, int dest)
{
    int flow = 0;
    while(bfs(source, dest))
    {
        int path_flow = INF, node = dest;
        while(node != source)
        {
            path_flow = min(path_flow, cap[parent[node]][node]);
            node = parent[node];
        }
        node = dest;
        while(node != source)
        {
            cap[parent[node]][node] -= path_flow;
            cap[node][parent[node]] += path_flow;
            node = parent[node];
        }
        flow += path_flow;
    }
    return flow;
}

int main()
{
    fin >> n >> m;
    while(m--)
    {
        int u, v, c;
        fin >> u >> v >> c;
        adj[u].push_back(v);
        adj[v].push_back(u);
        cap[u][v] = c;
    }
    fout << maxflow(1, n);

    return 0;
}