Cod sursa(job #2886974)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 8 aprilie 2022 17:27:31
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

const string filename = "maxflow";
ifstream fin(filename + ".in");
ofstream fout(filename + ".out");

const int maxN = 1005, inf = 0x3f3f3f3f;
int n, m, p[maxN], cap[maxN][maxN], flux[maxN][maxN], max_flow;
bool used[maxN];
vector <int> G[maxN];
queue <int> q;

bool bfs()
{
    for(int i = 1; i <= n; i++)
        used[i] = 0;
    q.push(1);
    used[1] = 1;
    while(!q.empty())
    {
        int nod = q.front();
        q.pop();
        for(int vecin : G[nod])
        {
            if(used[vecin])
                continue;
            if(cap[nod][vecin] > flux[nod][vecin])
            {
                p[vecin] = nod;
                used[vecin] = 1;
                q.push(vecin);
            }
        }
    }
    return used[n];
}

int main()
{
    fin >> n >> m;
    for(int x, y, c, i = 1; i <= m; i++)
    {
        fin >> x >> y >> c;
        G[x].push_back(y);
        G[y].push_back(x);
        cap[x][y] = c;
    }
    while(bfs())
    {
        int min_flow = inf;
        for(int x = n; x != 1; x = p[x])
            min_flow = min(min_flow, cap[p[x]][x] - flux[p[x]][x]);
        for(int x = n; x != 1; x = p[x])
        {
            flux[p[x]][x] += min_flow;
            flux[x][p[x]] -= min_flow;
        }
        max_flow += min_flow;
    }
    fout << max_flow;
    return 0;
}