Cod sursa(job #2988710)

Utilizator andreipirjol5Andrei Pirjol andreipirjol5 Data 5 martie 2023 13:14:14
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.38 kb
#include <fstream>
#include <iostream>
#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(int node)
{
    memset(father, 0, sizeof(father));
    father[1] = 1;

    while(!q.empty())
        q.pop();

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

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

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

        for(auto neigh : graph[e.dest])
        {
            if(father[neigh] == 0 and cap[e.dest][neigh] - flow[e.dest][neigh] > 0)
            {
                edge new_edge;
                new_edge.start = e.dest;
                new_edge.dest = neigh;

                father[neigh] = e.dest;

                q.push(new_edge);
            }
        }
    }

    return false;
}

int find_min(int node)
{
    int minim = cap[node][n] - flow[node][n];

    while(node != 1)
    {
        minim = min(minim, cap[father[node]][node] - flow[father[node]][node]);

        node = father[node];
    }

    return minim;
}

void update_flow(int node, int minim)
{
    while(node != 1)
    {
        flow[father[node]][node] += minim;
        flow[node][father[node]] -= minim;

        node = father[node];
    }
}

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;
        cap[y][x] += z;
        flow[y][x] += z;

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

    int ans = 0;

    while(bfs(n))
    {
        for(auto neigh : graph[n])
        {
            if(father[neigh] == 0)
                continue;

            int minim = find_min(neigh);
            update_flow(neigh, minim);

            flow[neigh][n] += minim;
            flow[n][neigh] -= minim;
        }
    }

    for(auto neigh : graph[n])
        ans += flow[neigh][n];

    fout << ans;

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