Cod sursa(job #2652972)

Utilizator Tudor_PascaTudor Pasca Tudor_Pasca Data 26 septembrie 2020 15:47:53
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

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

const int INF = 0x3f3f3f3f3f3f3f3f;
int N, M, maxFlow;
int cap[1010][1010], flow[1010][1010], father[1010];
bool use[1010];
vector<vector<int>> adj;

bool BFS()
{
    memset(father, 0, sizeof father);
    memset(use, false, sizeof use);
    queue<int> q;
    q.push(1);
    use[1] = true;

    while(!q.empty())
    {
        int node = q.front();

        q.pop();

        if(node == N)
            continue;

        for(auto i : adj[node])
        {
            if(!use[i] && (cap[node][i] - flow[node][i] > 0))
            {
                use[i] = true;
                father[i] = node;
                q.push(i);
            }
        }
    }

    return use[N];
}

int main()
{
    in >> N >> M;

    adj.resize(N + 5);

    for(int i = 1; i <= M; i++)
    {
        int x, y, c;
        in >> x >> y >> c;

        adj[x].push_back(y);
        adj[y].push_back(x);

        cap[x][y] = c;

        cap[y][x] = c;
        flow[y][x] = c;
    }

    while(BFS())
    {
        int bottleNeck = INF;

        for(int i = N; i != 1; i = father[i])
            bottleNeck = min(bottleNeck, cap[father[i]][i] - flow[father[i]][i]);

        for(int i = N; i != 1; i = father[i])
        {
            //cout << i << ' ';
            flow[father[i]][i] += bottleNeck;
            flow[i][father[i]] -= bottleNeck;
        }

        //cout << '\n';

        maxFlow += bottleNeck;
    }

    out << maxFlow << '\n';

    return 0;
}