Cod sursa(job #2960319)

Utilizator altaugeorgegeorge altaugeorge Data 4 ianuarie 2023 01:03:20
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.19 kb
#include <iostream>
#include <vector>
#include <queue>
#include <cstdio>
#include <bitset>
using namespace std;

const int MAXN = 1005;

//struct edge{
//    int capacity, flow;
//};

int n, m, x, y, c;
//edge matrix[MAXN][MAXN];
int capacity[MAXN][MAXN];
int flow[MAXN][MAXN];
int father[MAXN];
vector<pair<int, int>> ad[MAXN];
int source, destination;

bitset<MAXN> explored;

bool bfs() {

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

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

        for(auto it : ad[node]) {
            int i = it.first;
                if(flow[node][i] < capacity[node][i] && 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);
        capacity[x][y] = c;
        ad[x].push_back(make_pair(y, c));
        ad[y].push_back(make_pair(x, c));
    }

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

    while(bfs()) {

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

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

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