Cod sursa(job #3189239)

Utilizator NeganAlex Mihalcea Negan Data 4 ianuarie 2024 18:13:00
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.27 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];
pair<int, int>rezidual[1005][1005];


bool BFS()
{
    for(int i = 1;i <= n;i++)
        last[i] = viz[i] = aug_path[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 && (rezidual[nod][x].first - rezidual[nod][x].second) > 0 )
            {
                viz[x] = 1;
                last[x] = nod;
                q.push(x);
            }
    }
    if(viz[n])
        return true;
    return false;
}
void Solve()
{
    while(BFS())
    {
        for(auto frunza : V[n])
            if(viz[frunza])
            {
                int bottleneck = rezidual[frunza][n].first - rezidual[frunza][n].second;
                int nod = frunza;
                while(last[nod] != 0)
                {
                    bottleneck = min(bottleneck, rezidual[last[nod]][nod].first -
                                                 rezidual[last[nod]][nod].second);
                    nod = last[nod];
                }
                rezidual[frunza][n].second += bottleneck;
                rezidual[n][frunza].second -= bottleneck;
                nod = frunza;
                while(last[nod] != 0)
                {
                    rezidual[last[nod]][nod].second += bottleneck;
                    rezidual[nod][last[nod]].second -= 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);
        rezidual[x][y].first += c;
        rezidual[x][y].second = 0;
        rezidual[y][x] = {0, 0};
    }
}
int main()
{
    Citire();
    Solve();
    return 0;
}