Cod sursa(job #2368739)

Utilizator PaulTPaul Tirlisan PaulT Data 5 martie 2019 17:38:35
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.9 kb
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

using VI = vector<int>;
using VVI = vector<VI>;
using VB = vector<bool>;

const int Inf = 0x3f3f3f3f;
int n, m;
VB v;
VI t;
VVI G, C;
queue<int> Q;

void Read();
int MaxFlow(int source, int sink);
bool Bfs(int source, int sink);
void Write();

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

void Write()
{
    ofstream fout("maxflow.out");
    fout << MaxFlow(1, n);
    fout.close();
}

bool Bfs(int source, int sink)
{
    v = VB(n + 1);
    Q.push(source);
    v[source] = true;
    int x;
    while (!Q.empty())
    {
        x = Q.front();
        Q.pop();
        if (x == sink)
            continue;
        for (const int& y : G[x])
            if (!v[y] && C[x][y] > 0)
            {
                Q.push(y);
                v[y] = true;
                t[y] = x;
            }
    }
    return v[sink];
}

int MaxFlow(int source, int sink)
{
    int maxflow = 0, flow;
    while (Bfs(source, sink))
        for (const int& x : G[sink])
        {
            if (!v[x] || C[x][sink] <= 0)
                continue;
            flow = Inf;
            t[sink] = x;
            for (int i = sink; i != source; i = t[i])
                flow = min(flow, C[t[i]][i]);
            if (!flow)
                continue;
            for (int i = sink; i != source; i = t[i])
            {
                C[t[i]][i] -= flow;
                C[i][t[i]] += flow;
            }
            maxflow += flow;
        }
    return maxflow;
}

void Read()
{
    ifstream fin("maxflow.in");
    fin >> n >> m;
    G = VVI(n + 1);
    C = VVI(n + 1, VI(n + 1));
    t = VI(n + 1);
    int x, y, c;
    for (int i = 0; i < m; i++)
    {
        fin >> x >> y >> c;
        G[x].push_back(y);
        G[y].push_back(x);
        C[x][y] += c;
    }
    fin.close();
}