Cod sursa(job #2960311)

Utilizator anne_marieMessner Anne anne_marie Data 4 ianuarie 2023 00:32:30
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.99 kb

#include <iostream>
#include <vector>
#include <queue>
#include <cstdio>
#include <bitset>
using namespace std;


struct edge{
    int capacity, flow;
};

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

bitset<1005> explored;

bool bfs() {

    for(int i = 1; i <= n; i++) {
        father[i] = 0;
    }
    explored.reset();
    explored[source] = 1;
    q.push(source);

    while(!q.empty()) {
        int node = q.front();
        q.pop();
        if (node == destination) {
            while(!q.empty()) q.pop();
            return 1;
        }

        for(auto i : ad[node]) {
                if(matrix[node][i].flow < matrix[node][i].capacity && explored[i] == 0) {
                    explored[i] = 1;
                    q.push(i);
                    father[i] = node;
                }
        }
    }

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


int main() {
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);

    scanf("%d%d", &n, &m);

    for (int i = 1; i <= m; i++ )
    {
        scanf("%d%d%d", &x, &y, &c);
        matrix[x][y].capacity = c;
        ad[x].push_back(y);
        ad[y].push_back(x);
    }

    source = 1;
    destination = n;
    int max_flow = 0;

    while(bfs()) {

        int node = destination;
        int min_flow = 120000;

        // 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);
            node = father[node];
        }
        node = destination;
        max_flow += min_flow;

        while(father[node] != 0) {
            matrix[father[node]][node].flow += min_flow;
            matrix[node][father[node]].flow -= min_flow;
            node = father[node];
        }
    }

    printf("%d", max_flow);
    return 0;
}