Cod sursa(job #3363425)

Utilizator robertcosacCosac Robert-Mihai robertcosac Data 17 august 2026 22:43:31
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
vector <int> v[1009];
bool viz[1009];
queue <int> q;
int tata[1009], r[1009][1009], s, d, sol=0, n;
bool bfs ()
{
    for (int i=1; i<=n; i++)
        viz[i]=0, tata[i]=0;
    q.push(s);
    viz[s]=1;
    while (!q.empty())
    {
        int x=q.front();
        q.pop();
        for (auto y:v[x])
        {
            if (!viz[y] && r[x][y]>0)
            {
                viz[y]=1;
                tata[y]=x;
                q.push(y);
            }
        }
    }
    return viz[d];
}
void flux_maxim ()
{
    int flow=0;
    while (bfs())
    {
        for (auto y:v[d])
        {
            if ((tata[y]!=0 || y==s) && r[y][d]>0)
            {
                flow=r[y][d];
                for (int j=y; j!=s; j=tata[j])
                {
                    flow=min (flow, r[tata[j]][j]);
                    if (!flow)
                        break;
                }
            }
            if (flow)
            {
                r[y][d]-=flow;
                r[d][y]+=flow;
                for (int j=y; j!=s; j=tata[j])
                {
                    r[tata[j]][j]-=flow;
                    r[j][tata[j]]+=flow;
                }
                sol+=flow;
            }
        }
    }
}
signed main ()
{
    int m;
    f >> n >> m;
    for (int i=1; i<=m; i++)
    {
        int x, y, c;
        f >> x >> y >> c;
        v[x].push_back(y);
        v[y].push_back (x);
        r[x][y]+=c;
    }
    s=1, d=n;
    flux_maxim();
    g << sol;
}