Cod sursa(job #3231099)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 24 mai 2024 19:31:07
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
/// Preset de infoarena
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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

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

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

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