Cod sursa(job #3271527)

Utilizator StefantimStefan Timisescu Stefantim Data 26 ianuarie 2025 14:48:11
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include<bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int NMAX = 1e3 + 5;
vector < vector <int> > d(NMAX, vector<int> (NMAX));
vector <vector<int>> v(NMAX);
vector <int> p(NMAX);
int bfs(int s, int f)
{
    fill(p.begin(), p.end(), -1);
    p[s] = s;
    queue <pair<int,int>> q;
    q.push({s,INT_MAX});

    while(!q.empty())
    {
        auto [nod,flow] = q.front();
        q.pop();
        for(auto new_nod: v[nod])
        {
            if(p[new_nod] == -1 && d[nod][new_nod] > 0)
            {
                p[new_nod] = nod;
                int new_flow = min(flow, d[nod][new_nod]);
                if(new_nod == f)
                    return new_flow;
                q.push({new_nod,new_flow}); 
            }
        }
    }
    return 0;    
}

int maxflow(int s, int f)
{
    int flow, new_flow;
    flow = 0;
    while(new_flow = bfs(s,f))
    {
        flow += new_flow;
        int nod = f;
        while(nod != p[nod])
        {
            d[nod][p[nod]] += new_flow;
            d[p[nod]][nod] -= new_flow;
            nod = p[nod];
        }
    }
    return flow;
}

int main()
{
    int n, m, x, y, c;
    fin >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        fin >> x >> y >> c;
        d[x][y] = c;
        v[x].push_back(y);
    }
    fout << maxflow(1,n) << "\n";
}