Cod sursa(job #3321296)

Utilizator matei__bBenchea Matei matei__b Data 9 noiembrie 2025 00:15:27
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ld long double
#define pb push_back
#define mp make_pair
using namespace std;
 
constexpr const int NMAX=1e6+8;
constexpr const ll mod=1e9+7;
 
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

int n,m;
vector<int> g[1002];
int cap[1002][1002];
int p[1002];

int bfs(int s,int d)
{
    for(int i=1; i<=n; i++)
        p[i]=-1;
    p[s]=-2;
    queue<pair<int,int> > q;
    q.push(mp(s,INT_MAX));
    while(q.size())
    {
        int nod=q.front().first;
        int flow=q.front().second;
        q.pop();

        for(const auto &vec:g[nod])
        {
            if(p[vec]==-1 && cap[nod][vec])
            {
                p[vec]=nod;
                int newflow=min(flow,cap[nod][vec]);
                if(vec==d)
                    return newflow;
                q.push(mp(vec,newflow));
            }
        }
    }
    return 0;
}
int maxflow(int s,int d)
{
    int flow=0,newflow;
    while(newflow=bfs(s,d))
    {
        flow+=newflow;
        int curr=d;
        while(curr!=s)
        {
            int pp=p[curr];
            cap[pp][curr]-=newflow;
            cap[curr][pp]+=newflow;
            curr=pp;
        }
    }
    return flow;
}

void solve()
{
    fin >> n >> m;
    for(int i=1; i<=m; i++)
    {
        int x,y,w;
        fin >> x >> y >> w;
        g[x].pb(y);
        cap[x][y]=w;
    }
    fout << maxflow(1,n);
}   

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
 
    int tests=1;
    // cin >> tests;
    for(int i=1; i<=tests; i++)
        solve();
    
    return 0;
}