Cod sursa(job #2709645)

Utilizator PopescuAndreiAlexandruPopescu Andrei Alexandru PopescuAndreiAlexandru Data 20 februarie 2021 20:02:46
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.62 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <cstring>
#include <queue>
#include <stack>

using namespace std;

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

const int N = 1005;

int n, m, x, y, c, source, sink, Cap[N][N], Flow[N][N], t[N], seen[N], MaxFlow = 0;

vector<int> G[N];

void Read()
{
    fin >> n >> m;
    while (m--)
        {
            fin >> x >> y >> c;
            Cap[x][y] = c;
            G[x].push_back(y);
            G[y].push_back(x);
        }
    source = 1;
    sink = n;
}

bool BFS(int source, int sink)
{
    queue<int> Q;
    memset(seen, 0, sizeof(seen));
    memset(t, 0, sizeof(t));
    Q.push(source);
    seen[source] = 1;
    while (!Q.empty())
        {
            int nod = Q.front();
            Q.pop();
            vector<int>::iterator it;
            for (it = G[nod].begin(); it != G[nod].end(); it++)
                {
                    int next = (*it);
                    if (!seen[next] && Cap[nod][next] - Flow[nod][next] > 0)
                        {
                            seen[next] = 1;
                            t[next] = nod;
                            Q.push(next);
                        }
                }
        }
    if (!t[sink])
        return false;
    return true;
}

void FindFlow()
{
    while (BFS(source, sink))
        {
            vector<int>::iterator it;
            for (it = G[sink].begin(); it != G[sink].end(); it++)
                {
                    int next = (*it);
                    if (Cap[next][sink] - Flow[next][sink] > 0 && seen[next])
                        {
                            int Min = Cap[next][sink] - Flow[next][sink];
                            int p = next;
                            while (t[p])
                                {
                                    Min = min(Min, Cap[t[p]][p] - Flow[t[p]][p]);
                                    p = t[p];
                                }
                            p = next;
                            Flow[next][sink] += Min;
                            Flow[sink][next] -= Min;
                            while (t[p])
                                {
                                    Flow[t[p]][p] += Min;
                                    Flow[p][t[p]] -= Min;
                                    p = t[p];
                                }
                            MaxFlow += Min;
                        }
                }
        }
    fout << MaxFlow << '\n';
}

int main()
{
    Read();
    FindFlow();
}