Cod sursa(job #3364022)

Utilizator robertcosacCosac Robert-Mihai robertcosac Data 26 august 2026 21:55:57
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
struct elem
{
    int nod, poz;
};
int cnt=0;
vector <elem> v[1009];
bool viz[1009];
queue <int> q;
int s, d, sol=0, n;
elem tata[10009];
int r[10009];
bool bfs ()
{
    for (int i=1; i<=n; i++)
        viz[i]=0, tata[i]={0, 0};
    q.push(s);
    viz[s]=1;
    while (!q.empty())
    {
        int x=q.front();
        q.pop();
        for (auto y:v[x])
        {
            if (!viz[y.nod] && r[y.poz]>0)
            {
                viz[y.nod]=1;
                tata[y.nod].nod=x;
                tata[y.nod].poz=y.poz;
                q.push(y.nod);
            }
        }
    }
    return viz[d];
}
void flux_maxim ()
{
    int flow=0;
    while (bfs())
    {
        for (auto y:v[d])
        {
            if ((tata[y.nod].nod!=0 || y.nod==s) && r[y.poz^1]>0)
            {
                flow=r[y.poz^1];
                for (int j=y.nod; j!=s; j=tata[j].nod)
                {
                    flow=min (flow, r[tata[j].poz]);
                    if (!flow)
                        break;
                }
                if (flow)
                {
                    r[y.poz^1]-=flow;
                    r[y.poz]+=flow;
                    for (int j=y.nod; j!=s; j=tata[j].nod)
                    {
                        r[tata[j].poz]-=flow;
                        r[tata[j].poz^1]+=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, cnt});
        r[cnt]+=c;
        cnt++;
        v[y].push_back ({x, cnt});
        cnt++;
    }
    s=1, d=n;
    flux_maxim();
    g << sol;
}