Cod sursa(job #2960277)

Utilizator anne_marieMessner Anne anne_marie Data 3 ianuarie 2023 22:35:41
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.09 kb
#include <fstream>
#include <iostream>
#include <climits>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

struct edge{
    int capacity, flow;
};

int n, m, x, y, c;
edge matrix[1005][1005];
queue<int> q;
int father[1005];
int dist[1005];
int source, destination;


int bfs() {

    for(int i = 1; i <= n; i++) {
        dist[i] = INT_MAX;
    }

    dist[source] = 0;

    q.push(source);
    while(!q.empty()) {
        int node = q.front();
        q.pop();

        for(int i = 1; i <= n; i ++) {
            if(matrix[node][i].capacity != 0) {
                if(matrix[node][i].flow < matrix[node][i].capacity && dist[i] > dist[node] + 1) {
                    dist[i] = dist[node] + 1;
                    q.push(i);
                    father[i] = node;
                }
            }
        }
    }

    if(dist[destination] == INT_MAX)
        return 0; // destination can't be reached!
    else
        return 1; // destination reached!
}


int main() {
    fin >> n >> m;

    for (int i = 1; i <= m; i++ )
    {
        fin >> x >> y >> c;
        matrix[x][y].capacity = c;
        matrix[x][y].flow = 0;

        // residual matrix
        matrix[y][x].capacity = 0;
    }

    source = 1;
    destination = n;

    while(bfs()) {

        int node = destination;
        vector<int> path;
        int min_flow = INT_MAX;

        // calculate the maximal flow that can be pushed through this path
        while(father[node] != 0) {
            min_flow = min(min_flow, matrix[father[node]][node].capacity - matrix[father[node]][node].flow);
            path.push_back(node);
            node = father[node];
        }
        path.push_back(node);

        // pushing the flow
        reverse(path.begin(), path.end());
        for(int i = 0; i < path.size() - 1; i ++) {
            matrix[path[i]][path[i + 1]].flow += min_flow;
            matrix[path[i + 1]][path[i]].flow -= min_flow;
        }

    }

    int max_flow = 0;
    for(int i = 1; i <= n; i++) {
        max_flow += matrix[source][i].flow;
    }

    fout<< max_flow;
    return 0;
}