Cod sursa(job #3193190)

Utilizator pifaDumitru Andrei Denis pifa Data 14 ianuarie 2024 12:53:48
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <bits/stdc++.h>

using namespace std;

ifstream in("maxflow.in");
ofstream out("maxflow.out");

const int N = 1e3 + 5;

vector <int> g[N];

int n, m;

const int INF = 1e9;

int cap[N][N], flux[N][N], pred[N], viz[N];

bool bfs(int s, int t)
{
    memset(viz, 0, sizeof(viz));
    memset(pred, 0, sizeof(pred));
    viz[s] = 1;
    queue <int> q;
    q.push(s);
    while(q.size())
    {
        int cur = q.front();
        q.pop();
        for(auto next:g[cur])
        {
            if(!viz[next] && cap[cur][next] > 0)
            {
                viz[next] = 1;
                pred[next] = cur;
                q.push(next);
                if(next == t)
                {
                    return true;
                }
            }
        }
    }
    return false;
}

int main()
{
    in >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int x, y, capacitate;
        in >> x >> y >> capacitate;
        cap[x][y] += capacitate;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    int flux = 0;
    int s = 1, t = n;
    while(bfs(s, t))
    {
        for(auto nod:g[t])
        {
            if(!viz[nod] || cap[nod][t] <= 0)
            {
                continue;
            }
            pred[t] = nod;
            int x = t, minim = INF;
            while(x != s)
            {
                minim = min(minim, cap[pred[nod]][nod]);
                x = pred[x];
            }
            if(minim <= 0)
            {
                continue;
            }
            flux += minim;
            x = t;
            while(x != s)
            {
                cap[pred[x]][x] -= minim;
                cap[x][pred[x]] += minim;
                x = pred[x];
            }
        }
    }
    out << flux;
    return 0;
}