Cod sursa(job #2984191)

Utilizator SabailaCalinSabaila Calin SabailaCalin Data 23 februarie 2023 18:27:02
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.13 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

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

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

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;
    }
}

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

    queue <int> q;
    q.push(s);

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

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

            if (parent[neighbour] == 0 && capacity[node][neighbour] > 0)
            {
                parent[neighbour] = node;
                q.push(neighbour);

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

    return false;
}

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

    while (BFS(1, n) == true)
    {
        for (unsigned int i = 0; i < adj[t].size(); i++)
        {
            int node = adj[t][i];

            if (parent[node] == 0 || capacity[node][t] <= 0)  continue;

            parent[t] = node;
            int newFlow = INF;

            node = t;
            while (node != s)
            {
                int par = parent[node];
                newFlow = min(newFlow, capacity[par][node]);
                node = par;
            }

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

            flow += newFlow;
        }
    }

    return flow;
}

int main()
{
    Read();

    g << MaxFlow(1, n);

    return 0;
}