Cod sursa(job #2986799)

Utilizator andreipirjol5Andrei Pirjol andreipirjol5 Data 1 martie 2023 11:13:09
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
#include <cstring>

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

const int INF = INT_MAX;

const int NMAX = 1e3;
vector <int> graph[NMAX + 5];
int cap[NMAX + 5][NMAX + 5], flow[NMAX + 5][NMAX + 5];
int n;

struct edge
{
    int start, dest;
};

queue <edge> q;
int father[NMAX + 5];

bool bfs()
{
    edge first;
    first.start = 0;
    first.dest = 1;
    q.push(first);

    while(!q.empty())
    {
        edge e = q.front();
        q.pop();

        father[e.dest] = e.start;

        if(e.dest == n)
            return true;

        for(auto neigh : graph[e.dest])
        {
            if(cap[e.dest][neigh] - flow[e.dest][neigh])
            {
                edge new_edge;
                new_edge.start = e.dest;
                new_edge.dest = neigh;
                q.push(new_edge);
            }
        }
    }

    return false;
}

int find_min(int node)
{
    if(node == 1)
        return INF;

    return min(find_min(father[node]), cap[father[node]][node] - flow[father[node]][node]);
}

void update_flow(int node, int minim)
{
    if(father[node] == 1)
    {
        flow[1][node] += minim;
        flow[node][1] -= minim;
        return;
    }

    flow[father[node]][node] += minim;
    flow[node][father[node]] -= minim;
    update_flow(father[node], minim);
}

int main()
{
    int m;
    fin >> n >> m;

    for(int i = 1; i <= m; i++)
    {
        int x, y, z;
        fin >> x >> y >> z;

        cap[x][y] = z;
        flow[x][y] = 0;
        flow[y][x] = z;

        graph[x].push_back(y);
        graph[y].push_back(x);
    }

    while(bfs())
    {
        int minim = find_min(n);
        update_flow(n, minim);
    }

    int ans = 0;
    for(int i = 1; i <= n; i++)
    {
        if(flow[i][n] >= 0)
            ans += flow[i][n];
    }

    fout << ans;
    fin.close();
    fout.close();
    return 0;
}