Cod sursa(job #3253531)

Utilizator MikeStrikeAgache Mihai MikeStrike Data 3 noiembrie 2024 03:08:27
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#include <climits>

using namespace std;

const int MAXN = 1001;
int capacity[MAXN][MAXN]; 
int flow[MAXN][MAXN];     
vector<int> adj[MAXN];    

int bfs(int source, int sink, vector<int>& parent, int n) {
    fill(parent.begin(), parent.end(), -1);
    parent[source] = -2;    
    queue<pair<int, int>> q;
    q.push({source, INT_MAX});

    while (!q.empty()) {
        int u = q.front().first;
        int current_flow = q.front().second;
        q.pop();

        for (int v : adj[u]) {
            if (parent[v] == -1 && capacity[u][v] - flow[u][v] > 0) {
                parent[v] = u;
                int new_flow = min(current_flow, capacity[u][v] - flow[u][v]);
                if (v == sink)
                    return new_flow;                 
                q.push({v, new_flow});
            }
        }
    }
    return 0; 
}

int edmondsKarp(int source, int sink, int n) {
    int max_flow = 0;
    vector<int> parent(n + 1);

    int new_flow;
    while ((new_flow = bfs(source, sink, parent, n)) > 0) {
        max_flow += new_flow;
        int v = sink;

        while (v != source) {
            int u = parent[v];
            flow[u][v] += new_flow;
            flow[v][u] -= new_flow;
            v = u;
        }
    }

    return max_flow;
}

int main() {
    ifstream in("maxflow.in");
    ofstream out("maxflow.out");

    int N, M;
    in >> N >> M;

    for (int i = 0; i < M; i++) {
        int x, y, z;
        in >> x >> y >> z;
        capacity[x][y] += z;         
        adj[x].push_back(y);
        adj[y].push_back(x);    
    }

    int source = 1, sink = N;     
    int max_flow = edmondsKarp(source, sink, N);

    out << max_flow << endl;


    return 0;
}