Cod sursa(job #2093536)

Utilizator amaliarebAmalia Rebegea amaliareb Data 23 decembrie 2017 22:41:32
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>

using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
const int MaxN = 1005;
int n, m, cap[MaxN][MaxN], flow[MaxN][MaxN], from[MaxN], ok, maxfl = 0, added, np;
vector<int> gr[5 * MaxN];

bool bfs()
{
    queue<int> q;
    bool viz[MaxN];
    memset(from, 0, sizeof(from));
    memset(viz, 0, sizeof(viz));
    viz[1] = 1;
    q.push(1);
    while (!q.empty() && !viz[n])
    {
        int node = q.front();
        q.pop();
        for (auto son: gr[node])
        {
            if (!viz[son] && flow[node][son] < cap[node][son])
            {
                viz[son] = 1;
                q.push(son);
                from[son] = node;
            }
        }
    }
    if (viz[n]) return 1;
    return 0;
}

int main()
{
    f >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        int x, y, c;
        f >> x >> y >> c;
        gr[x].push_back(y);
        cap[x][y] = c;
        gr[y].push_back(x);
        ///cap[y][x] = 0;
    }
    ok = 1;
    added = 1;
    while (bfs())
    {
        for (int i = 1; i < n; ++i)
            if (from[i] && flow[i][n] < cap[i][n])
            {
                added = cap[i][n] - flow[i][n];
                from[n] = i;
                int node = n;
                while (from[node])
                {
                    added = min(added, cap[from[node]][node] - flow[from[node]][node]);
                    node = from[node];
                }
                node = n;
                while (from[node])
                {
                    flow[from[node]][node] += added;
                    flow[node][from[node]] -= added;
                    node = from[node];
                }
                maxfl += added;
            }
    }
    g << maxfl << '\n';
    return 0;
}