Cod sursa(job #2587589)

Utilizator trifangrobertRobert Trifan trifangrobert Data 23 martie 2020 02:10:30
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 1005;
const int INF = (1 << 30);
int N, M;
int residual_graph[NMAX][NMAX];
vector <int> graph[NMAX];
int father[NMAX];

bool bfs()
{
    for (int i = 1;i <= N;++i)
        father[i] = 0;
    queue <int> q;
    bitset <NMAX> seen;
    q.push(1);
    seen[1] = 1;
    while (!q.empty())
    {
        int node = q.front();
        q.pop();
        for (auto& x : graph[node])
            if (seen[x] == 0 && residual_graph[node][x] > 0)
            {
                seen[x] = 1;
                q.push(x);
                father[x] = node;
            }
    }
    return seen[N];
}

int main()
{
    ifstream fin("maxflow.in");
    ofstream fout("maxflow.out");
    fin >> N >> M;
    for (int i = 1;i <= M;++i)
    {
        int u, v, c;
        fin >> u >> v >> c;
        graph[u].push_back(v);
        graph[v].push_back(u);
        residual_graph[u][v] += c;
    }
    int maxflow = 0;
    while (bfs())
    {
        for (auto& x : graph[N])
        {
            if (father[x] == 0)
                continue;
            father[N] = x;
            int mn = INF;
            for (int now = N;now != 1;now = father[now])
            {
                int u = father[now];
                int v = now;
                mn = min(mn, residual_graph[u][v]);
            }
            for (int now = N;now != 1;now = father[now])
            {
                int u = father[now];
                int v = now;
                residual_graph[u][v] -= mn;
                residual_graph[v][u] += mn;
            }
            maxflow += mn;
        }
    }
    fout << maxflow << "\n";
    fin.close();
    fout.close();
    return 0;
}