Cod sursa(job #2987515)

Utilizator andreipirjol5Andrei Pirjol andreipirjol5 Data 2 martie 2023 14:18:35
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.07 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()
{
    memset(father , 0 , sizeof(father));

    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])
            {
                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 = INF;

    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())
    {
        int minim = find_min(n);

        update_flow(n, minim);

        ans += minim;
    }

    fout << ans;

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