Cod sursa(job #3219414)

Utilizator AswVwsACamburu Luca AswVwsA Data 31 martie 2024 12:54:48
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <fstream>
#include <vector>
#include <queue>
#define ll long long
using namespace std;

const int NMAX = 1000;
const int MMAX = 5000;
const int INF = 1e9;

struct edge
{
    int a, b, cap, f;
    int comp;
    bool org;
};

vector <pair <int, int> > g[NMAX + 1];

edge v[2 * MMAX + 1];

queue <int> q;

bool viz[NMAX + 1];
int mn[NMAX + 1];
int tata[NMAX + 1];
int what[NMAX + 1]; //muchia de la nod la ta-su din bfs
int n, m;

bool exists;

void augmentpath()
{
    int i;
    for (i = 1; i <= n; i++)
    {
        viz[i] = 0;
        mn[i] = INF;
    }
    mn[1] = INF;
    viz[1] = 1;
    q.push(1);
    tata[1] = 0;
    while (!q.empty())
    {
        int f = q.front();
        q.pop();
        for (pair <int, int> x : g[f])
            if (!viz[x.first] and v[x.second].cap != v[x.second].f)
            {
                tata[x.first] = f;
                viz[x.first] = 1;
                what[x.first] = x.second;
                int pump = v[x.second].cap - v[x.second].f;
                mn[x.first] = min(mn[f], pump);
                q.push(x.first);
            }
    }
    exists = viz[n];
}

signed main()
{
    ifstream cin("maxflow.in");
    ofstream cout("maxflow.out");
    int i, j;
    cin >> n >> m;
    for (i = 1; i <= m; i++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        v[2 * i - 1] = {a, b, c, 0, 2 * i, 1};
        v[2 * i] = {b, a, c, c, 2 * i - 1, 0};

        g[a].push_back({b, 2 * i - 1});
        g[b].push_back({a, 2 * i});
    }
    exists = 0;
    augmentpath();
    int flow = 0;
    while (exists)
    {
        int val = mn[n];
        flow += val;
        for (i = n; i != 0; i = tata[i])
        {
            v[what[i]].f += val;
            v[v[what[i]].comp].f -= val;
        }
        augmentpath();
    }
    cout << flow;
}