Cod sursa(job #3337342)

Utilizator ioan19Buzdugan Ioan-Michael ioan19 Data 27 ianuarie 2026 11:41:01
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>

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

const int NMAX = 1005, INF = INT_MAX;
int capacity[NMAX][NMAX], N, M;
vector<int> adj[NMAX];

int bfs(int s, int t, vector<int>& parent){
    fill(parent.begin(), parent.end(), -1);
    parent[s] = -2;
    queue<pair<int, int>> q;
    q.push({s, INF});

    while(!q.empty()){
        int nod = q.front().first;
        int flow = q.front().second;
        q.pop();

        for(int u : adj[nod])
            if(parent[u] == -1 && capacity[nod][u]){
                parent[u] = nod;
                int new_flow = min(flow, capacity[nod][u]);

                if(u == t)
                    return new_flow;

                q.push({u, new_flow});
            }
    }
    return 0;
}

int maxflow(int s, int t){
    vector<int> parent(N + 1, -1);
    int flow = 0, new_flow;

    while(new_flow = bfs(s, t, parent)){
        flow += new_flow;
        int curr = t;

        while(curr != s){
            int prev = parent[curr];
            capacity[prev][curr] -= new_flow;
            capacity[curr][prev] += new_flow;
            curr = prev;
        }
    }
    return flow;
}

int main(){
    f >> N >> M;
    for(int i = 1; i <= M; i++){
        int u, v, cost;
        f >> u >> v >> cost;
        
        if(capacity[u][v] == 0 && capacity[v][u] == 0){
            adj[u].push_back(v);
            adj[v].push_back(u);
        }

        capacity[u][v] += cost;
    }

    g << maxflow(1, N);

    return 0;
}