Cod sursa(job #3189975)

Utilizator FastmateiMatei Mocanu Fastmatei Data 6 ianuarie 2024 18:34:22
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

vector<int>v[1005];
int n, m;
int pred[1005];
queue<int>q;
int cap[1005][1005];
int flow[1005][1005];
int viz[1005];

int BFS()
{
    q.push(1);
    for (int i = 1; i <= n; i++)
        pred[i] = 0;
    while (!q.empty())
    {
        int x = q.front();
        q.pop();
        if (x == n) continue;
        for (auto w : v[x])
            if (pred[w]==0 && cap[x][w] > flow[x][w])
            {
                pred[w] = x;
                q.push(w);
            }
    }
    return pred[n];
}

int main()
{
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        v[x].push_back(y);
        v[y].push_back(x);
        cap[x][y] = c;
    }
    int flux = 0;
    int cnt = 0;
    while(BFS())
    {
        for (auto w : v[n])
        {
            if (pred[w] != 0)
            {
                int mn = cap[w][n] - flow[w][n];
                for (int x = w; x != 1; x = pred[x])
                    mn = min(mn, cap[pred[x]][x] - flow[pred[x]][x]);
                flow[w][n] += mn;
                flow[n][w] -= mn;
                for (int x = w; x != 1; x = pred[x])
                {
                    flow[pred[x]][x] += mn;
                    flow[x][pred[x]] -= mn;
                }
                flux += mn;
            }
        }
    }
    fout << flux << "\n";
    return 0;
}