Cod sursa(job #2955634)

Utilizator vladadAndries Vlad Andrei vladad Data 17 decembrie 2022 14:44:45
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
int n, m, cap[1001][1001];
vector<pair<int, int>> v[1001];
bool bfs(int s, int t, vector<int>& dad)
{
    fill(dad.begin(), dad.end(), -1);
    queue<int> q;
    q.push(s);
    dad[s] = -2;
    while(!q.empty())
    {
        int node = q.front();
        q.pop();
        for(auto next : v[node])
        {
            if(dad[next.first] == -1 && cap[node][next.first] > 0)
            {
                dad[next.first] = node;
                ///daca ajungem la terminal, returnam true
                if(next.first == t)
                    return true;
                q.push(next.first);
            }
        }
    }
    return false;
}

void flow()
{
    int max_flow = 0, s = 1, t = n;
    vector<int> dad(1001, -1);
    while(bfs(s, t, dad))
    {
        for(auto next : v[n])
        {
            if(dad[next.first] == -1 || cap[next.first][n] == 0)
                continue;
            dad[n] = next.first;
            int path_flow = INT_MAX;
            ///gasim fluxul maxim prin path
            for(int node = t; node != s; node = dad[node])
            {
                int aux = dad[node];
                path_flow = min(path_flow, cap[aux][node]);
            }
            if(path_flow == 0)
                continue;
            /// trimitem flux
            for(int node = t; node != s; node = dad[node])
            {
                int aux = dad[node];
                cap[aux][node] -= path_flow;
                cap[node][aux] += path_flow;
            }
            max_flow += path_flow;
        }
    }
    g << max_flow << '\n';
}

int main()
{
    f >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        int x, y, z;
        f >> x >> y >> z;
        v[x].push_back({y, z});
        v[y].push_back({x, z});
        cap[x][y] = z;
    }
    flow();
    return 0;
}