Cod sursa(job #3359980)

Utilizator Cristian_NegoitaCristian Negoita Cristian_Negoita Data 7 iulie 2026 13:14:07
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 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, capacity[NMAX][NMAX], parent[NMAX];
vector<int> adj[NMAX];

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

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

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

    return 0;
}