Cod sursa(job #3335900)

Utilizator temp1234Temp Mail temp1234 Data 23 ianuarie 2026 20:24:03
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

const int nmax = 1000;
int n, m, c[nmax + 1][nmax + 1];
vector<int> adj[nmax + 1];

void citire() {
    fin >> n >> m;
    for(int i = 1; i <= m; i ++) {
        int x, y, cap;
        fin >> x >> y >> cap;
        adj[x].push_back(y);
        adj[y].push_back(x);
        c[x][y] = cap;
        c[y][x] = 0;
    }
}


int tata[nmax + 1];
bool bfs(int start, int final) {
    for(int i = 1; i <= n; i ++)
        tata[i] = 0;
    
    queue<int> q;
    q.push(start);
    tata[start] = -1;

    while(!q.empty()) {
        int curr_node = q.front();
        q.pop();

        if(curr_node == final)
            return true;

        for (auto &v : adj[curr_node]){
            if(tata[v] == 0 && c[curr_node][v] > 0) {
                tata[v] = curr_node;
                q.push(v);
            }
        }
    }

    return false;
}

int main() {
    citire();
    int s = 1, t = n;
    int max_flow = 0;
    while(bfs(s, t)) {
        int bottleneck = INT_MAX;
        for(int nod = t; nod != s; nod = tata[nod]) {
            bottleneck = min(bottleneck, c[tata[nod]][nod]);
        }

        for(int nod = t; nod != s; nod = tata[nod]) {
            int parinte = tata[nod];
            c[parinte][nod] -= bottleneck;
            c[nod][parinte] += bottleneck;
        }

        max_flow += bottleneck;
    }
    fout << max_flow;
    return 0;
}