Cod sursa(job #2861329)

Utilizator qweryclujRadu Alexandru qwerycluj Data 3 martie 2022 20:18:36
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.4 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

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

#define Nmax 1005

int n, m;
std::vector<vector<int>>graf;
int C[Nmax][Nmax];
int F[Nmax][Nmax];
bool viz[Nmax];
int T[Nmax];
std::vector<int> N_paths;

bool BFS()
{
    memset(viz, false, Nmax);
    queue<pair<int, int>> q;
    viz[1] = true;

    for(int nod : graf[1])
    {
        if(C[1][nod] > F[1][nod])
        {
            viz[nod] = true;
            q.push({1, nod});
        }
    }

    while(!q.empty())
    {
        pair <int, int> act = q.front();
        q.pop();

        T[act.second] = act.first;

        if(act.second == n)
        {
            N_paths.push_back(act.first);
            continue;
        }

        for(int nod : graf[act.second])
        {
            if(!viz[nod] && C[act.second][nod] > F[act.second][nod])
            {
                if(nod != n)
                {
                    viz[nod] = true;
                }
                q.push({act.second, nod});
            }
        }
    }

    if(N_paths.size() != 0)
        return true;
    return false;
}

int main()
{
    fin >> n;
    fin >> m;
    graf = vector<vector<int>>(n + 1);
    int x, y;
    for(int i = 0; i < m; i++)
    {
        fin >> x >> y >> C[x][y];
        graf[x].push_back(y);
        //graf[y].push_back(x);
    }

    int maxflow = 0;
    while(BFS())
    {
        for(int path: N_paths)
        {
            int path_save = path;
            int minim = 2e9;
            int prev = n;
            if(C[path][prev] - F[path][prev] < minim)
            {
                minim = C[path][prev] - F[path][prev];
            }
            while(path != 1)
            {
                prev = path;
                path = T[path];
                if(C[path][prev] - F[path][prev] < minim)
                {
                    minim = C[path][prev] - F[path][prev];
                }
            } 
            
            if(minim < 1)
            {
                continue;
            }

            path = path_save;
            prev = n;
            F[path][prev] += minim;
            while(path != 1)
            {
                prev = path;
                path = T[path];
                F[path][prev] += minim;
            }
            maxflow += minim;
        }

        N_paths.clear();
    }
    fout << maxflow;
    return 0;
}