Cod sursa(job #2093517)

Utilizator amaliarebAmalia Rebegea amaliareb Data 23 decembrie 2017 22:03:29
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>

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;
bool viz[MaxN];
vector<int> gr[5 * MaxN];

bool dfs(int node)
{
    viz[node] = 1;
    if (node == n) return 1;
    bool path = 0;
    for (auto son: gr[node])
    {
        if (!viz[son] && flow[node][son] < cap[node][son]) path |= dfs(son);
        if (path)
        {
            from[++np] = son;
            break;
        }
    }
    return path;
}

int main()
{
    f >> n >> m;
    int m2 = 0;
    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 (added != 0)
    {
        np = 0;
        memset(viz, 0, sizeof(viz));
        added = 1 << 30;
        if(!dfs(1)) added = 0;
        else
        {
            from[++np] = 1;
            for (int i = 1; i < np; ++i)
                added = min(added, cap[from[i + 1]][from[i]] - flow[from[i + 1]][from[i]]);
            for (int i = 1; i < np; ++i)
                flow[from[i + 1]][from[i]] += added,
                flow[from[i]][from[i + 1]] -= added;
            maxfl += added;
        }
    }
    g << maxfl << '\n';
    return 0;
}