Cod sursa(job #3189253)

Utilizator NeganAlex Mihalcea Negan Data 4 ianuarie 2024 18:30:18
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.18 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, maxFlow = 0, m;
int viz[1005];
int aug_path[1005];
int last[1005];

struct elem
{
    int node, cap, flow;
};
vector<int>V[1005];
int capacitate[1005][1005];
int flow[1005][1005];


bool BFS()
{
    for(int i = 1;i <= n;i++)
       viz[i] = 0;
    queue<int>q;
    q.push(1);
    viz[1] = 1;
    while(!q.empty())
    {
        int nod = q.front();
        //cout << nod << " ";
        q.pop();
        if(nod == n)
            continue;
        for(auto x : V[nod])
            if(viz[x] == 0 && (capacitate[nod][x] > flow[nod][x]))
            {
                viz[x] = 1;
                last[x] = nod;
                q.push(x);
            }
    }
    if(viz[n])
        return true;
    return false;
}
void Solve()
{
    int bottleneck = 0;
    maxFlow = 0;
    while(BFS())
    {
        for(auto frunza : V[n])
            if(viz[frunza])
            {
                bottleneck = capacitate[frunza][n] - flow[frunza][n];
                int nod = frunza;
                while(last[nod] != 0)
                {
                    bottleneck = min(bottleneck, capacitate[last[nod]][nod] -
                                                 flow[last[nod]][nod]);
                    nod = last[nod];
                }
                if(!bottleneck) continue;
                flow[frunza][n] += bottleneck;
                flow[n][frunza] -= bottleneck;
                nod = frunza;
                while(last[nod] != 0)
                {
                    flow[last[nod]][nod] += bottleneck;
                    flow[nod][last[nod]] -= bottleneck;
                    nod = last[nod];
                }
                maxFlow += bottleneck;
                //cout << bottleneck << " ";
            }
    }
    fout << maxFlow;
}

void Citire()
{
    fin >> n >> m;
    for(int i = 1;i <= m;i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        V[x].push_back(y);
        V[y].push_back(x);
        capacitate[x][y] += c;
    }
}
int main()
{
    Citire();
    Solve();
    return 0;
}