Cod sursa(job #3337055)

Utilizator ioan19Buzdugan Ioan-Michael ioan19 Data 26 ianuarie 2026 21:32:00
Problema Flux maxim Scor 40
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 INF = INT_MAX, NMAX = 1005;
int N, M, capacity[NMAX][NMAX];
bool v[NMAX];
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 curr = q.front().first;
        int flow = q.front().second;
        q.pop();

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

                if(next == t)
                    return new_flow;

                q.push({next, new_flow});
            }
        }

    }
    return 0;
}
int maxflow(int s, int t){
    int flow = 0;
    vector<int> parent(NMAX);
    int 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 x, y, cost;
        f >> x >> y >> cost;
        adj[x].push_back(y);
        capacity[x][y] = cost;
        adj[y].push_back(x);
        capacity[y][x] = 0;
    }

    g << maxflow(1, N);

    return 0;
}