Cod sursa(job #2961102)

Utilizator andriciucandreeaAndriciuc Andreea andriciucandreea Data 5 ianuarie 2023 19:45:46
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.09 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <climits>

using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

int N, M;
vector <int> adj[1005];
vector <bool> vis;
vector <int> parent;
int capacity[1005][1005];

int BFS(int start, int end)
{
    parent.resize(N + 5);
    vis.resize(N + 5);
    fill(parent.begin(), parent.end(), -1);
    fill(vis.begin(), vis.end(), false);
    parent[start] = -2;
    vis[start] = true;
    queue <int> q;
    q.push(start);

    while (!q.empty())
    {
        int current = q.front();
        q.pop();

        for (int next : adj[current])
        {
            if (!vis[next] && capacity[current][next])
            {
                parent[next] = current;
                if (next == end)
                    return true;
                vis[next] = true;
                q.push(next);
            }
        }
    }
    return false;
}


int MaxFlow(int start, int end)
{
    int max_flow = 0;
    
    while (BFS(start, end))
    {
        for (int x : adj[end])
        {
            if (vis[x] && capacity[x][end] > 0)
            {
                parent[end] = x;
                int flow = INT_MAX;

                for (int node = end; node != start; node = parent[node])
                    flow = min(flow, capacity[parent[node]][node]);

                for (int node = end; node != start; node = parent[node])
                {
                    capacity[parent[node]][node] -= flow;
                    capacity[node][parent[node]] += flow;
                }

                max_flow += flow;
            }
        }
    }

    return max_flow;
}

int main()
{
    fin >> N >> M;
    int source = 1, dest = N;
    for (auto& line : adj)
        line.resize(N + 5, 0);
    while(M)
    {
        int x, y, cap;
        fin >> x >> y >> cap;
        capacity[x][y] = cap;
        adj[x].push_back(y);
        adj[y].push_back(x);
        M--;
    }
    int maxFlow = MaxFlow(source, dest);
    fout << maxFlow << endl;
}