Cod sursa(job #3040327)

Utilizator BorodiBorodi Bogdan Borodi Data 29 martie 2023 19:18:33
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include <fstream>
#include <vector>
#include <stack>
#include <stack>
#include <queue>
#include <algorithm>
#include <map>
#include <deque>
#include <cstring>
#define Nmax 281
using namespace std;

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

int n, x, y, c, m;
int C[Nmax][Nmax], F[Nmax][Nmax], Dad[Nmax];
vector <int> V[Nmax];
int oo = 1 << 28;

int BFS(int vertex){
    queue <int> Q;
    Q.push(vertex);
    memset(Dad, 0 , sizeof(Dad));

    while(!Q.empty()){
        vertex = Q.front();
        Q.pop();

        for(auto new_vertex : V[vertex])
            if(C[vertex][new_vertex] != F[vertex][new_vertex] && !Dad[new_vertex]){
                Dad[new_vertex] = vertex;
                Q.push(new_vertex);

                if(new_vertex == n)
                    return 1;
            }
    }
    return 0;
}

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

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

        V[x].push_back(y);
        V[y].push_back(x);
        C[x][y] += c;
    }

    int flow = 0;

    while(BFS(1)){
        for(auto vertex : V[n])
            if(Dad[vertex] && F[vertex][n] != C[vertex][n]){
                int mini = oo;
                Dad[n] = vertex;

                for(int vertice = n; vertice != 1; vertice = Dad[vertice])
                    mini = min(mini, C[Dad[vertice]][vertice] - F[Dad[vertice]][vertice]);
                
                for(int vertice = n; vertice != 1; vertice = Dad[vertice]){
                    F[Dad[vertice]][vertice] += mini;
                    F[vertice][Dad[vertice]] -= mini;
                }
                flow += mini;
            }
    }

    if(!flow)
        fout << "Apa nu ajunge!";
    else
        fout << flow;

    return 0;
}