Cod sursa(job #2983188)

Utilizator SabailaCalinSabaila Calin SabailaCalin Data 21 februarie 2023 19:41:27
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

const int SIZE = 1005;
const int INF = 0x3f3f3f3f;

ifstream f ("maxflow.in");
ofstream g ("maxflow.out");

int n, m;
int parent[SIZE];
int capacity[SIZE][SIZE];

vector <int> adj[SIZE];

void Read()
{
    f >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, z;
        f >> x >> y >> z;
        adj[x].push_back(y);
        adj[y].push_back(x);
        capacity[x][y] += z;
    }
}

int BFS(int s, int t)
{
    memset(parent, -1, sizeof(parent));
    parent[s] = -2;

    queue < pair <int, int> > q;
    q.push(make_pair(s, INF));

    while (q.empty() == false)
    {
        int node = q.front().first;
        int flow = q.front().second;
        q.pop();

        for (unsigned int i = 0; i < adj[node].size(); i++)
        {
            int neighbour = adj[node][i];

            if (parent[neighbour] == -1 && capacity[node][neighbour] != 0)
            {
                parent[neighbour] = node;
                int newFlow = min(flow, capacity[node][neighbour]);
                q.push(make_pair(neighbour, newFlow));

                if (neighbour == t)
                {
                    return newFlow;
                }
            }
        }
    }

    return 0;
}

int MaxFlow(int s, int t)
{
    int flow = 0, newFlow = 0;

    while ((newFlow = BFS(s, t)) != 0)
    {
        flow += newFlow;
        int node = t;

        while (node != s)
        {
            int par = parent[node];
            capacity[par][node] -= newFlow;
            capacity[node][par] += newFlow;
            node = par;
        }
    }

    return flow;
}

int main()
{
    Read();

    g << MaxFlow(1, n);
}