Cod sursa(job #3235721)

Utilizator Alex_BerbescuBerbescu Alexandru Alex_Berbescu Data 20 iunie 2024 18:37:32
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
// ford fulkerson
#pragma GCC optimize("O3")
#pragma GCC optimize("fast-math")
#pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
const int dim = 1e3 + 5;
int n, m, x, y, z;
bitset<dim>viz;
int tata[dim], maxflowu, pathflow;
vector<int>noduri[dim];
int mat[dim][dim];
bool bfs(int source, int terminal)
{
    tata[source] = -1;
    viz.reset();
    queue<int>q;
    q.push(source);
    viz[source] = 1;
    while(!q.empty())
    {
        int x = q.front();
        q.pop();
        for(auto it: noduri[x])
        {
            if(viz[it] == 0 && mat[x][it] > 0)
            {
                if(it == terminal)
                {
                    tata[terminal] = x;
                    return 1;
                }
                q.push(it);
                tata[it] = x;
                viz[it] = 1;
            }
        }
    }
    return 0;
}
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int32_t main(int argc, char * argv[])
{
    fin >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        fin >> x >> y >> z;
        noduri[x].push_back(y);
        mat[x][y] = z;
    }
    while(bfs(1, n) == 1)
    {
        pathflow = inf;
        for(int u = n; u != 1; u = tata[u])
        {
            int vo = tata[u];
            pathflow = min(pathflow, mat[vo][u]);
        }
        for(int u = n; u != 1; u = tata[u])
        {
            int vo = tata[u];
            mat[vo][u] -= pathflow;
            mat[u][vo] += pathflow;
        }
        maxflowu += pathflow;
    }
    fout << maxflowu;
    return 0;
}