Cod sursa(job #2408286)

Utilizator alex.mercan2014Mercan Alexandru alex.mercan2014 Data 17 aprilie 2019 19:31:04
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <limits>

using namespace std;

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

int const inf = numeric_limits<int>::max();
int n, m;

int bfs(vector<vector<int>> const &adjList, vector<vector<int>> &capacity, vector<int> &parent)
{
    fill(parent.begin(), parent.end(), -1);
    parent[1] = -2;
    queue<pair<int, int>> Q;
    Q.push(make_pair(1, inf));
    while (Q.empty() == false)
    {
        int current = Q.front().first;
        int flow = Q.front().second;
        Q.pop();
        for (auto next : adjList[current])
        {
            if (parent[next] == -1 && capacity[current][next])
            {
                parent[next] = current;
                int new_flow = min(flow, capacity[current][next]);
                if (next == n)
                    return new_flow;
                Q.push(make_pair(next, new_flow));
            }
        }
    }
    return 0;
}

void maxflow(vector<vector<int>> const &adjList, vector<vector<int>> &capacity)
{
    int flow = 0;
    vector<int> parent(n + 1);
    int new_flow;
    while (new_flow = bfs(adjList, capacity, parent))
    {
        flow += new_flow;
        int current = n;
        while (current != 1)
        {
            int prev = parent[current];
            capacity[prev][current] -= new_flow;
            capacity[current][prev] += new_flow;
            current = prev;
        }
    }
    fout << flow;
}

int main()
{
    fin >> n >> m;
    vector<vector<int>> capacity(n + 1, vector<int>(n + 1, 0)), adjList(n + 1);
    for (int i = 0; i < m; i++)
    {
        int x, y, z;
        fin >> x >> y >> z;
        adjList[x].push_back(y);
        adjList[y].push_back(x);
        capacity[x][y] = z;
    }
    maxflow(adjList, capacity);
    return 0;
}