Cod sursa(job #3227597)

Utilizator AnSeDraAndrei Sebastian Dragulescu AnSeDra Data 2 mai 2024 10:00:50
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.6 kb
#include <fstream>
#include <queue>

using namespace std;

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

const int Nmax = 1005;
const int Mmax = 5005;
const int CapMax = 110005;

struct nod{
    int adj, parent, edge;
};

struct muchie{
    int capacitate, nod, next;
};

int n, m;
nod noduri[Nmax];
muchie muchii[2 * Mmax];
queue<int> q;

void add_edge(int nod1, int nod2, int capacitate){
    static int poz = 0;

    muchii[poz] = {capacitate, nod2, noduri[nod1].adj};
    noduri[nod1].adj = poz++;
}

void citire(){
    int nod1, nod2, cap;

    fin >> n >> m;

    for(int i = 1; i <= n; i++){
        noduri[i].adj = -1;
    }

    for(int i = 1; i <= m; i++){
        fin >> nod1 >> nod2 >> cap;
        add_edge(nod1, nod2, cap);
        add_edge(nod2, nod1, 0);
    }
}

bool can_reach_end_bfs(){
    for(int i = 1; i <= n; i++){
        noduri[i].parent = -1;
    }

    while(!q.empty()){
        q.pop();
    }
    q.push(1);

    while(!q.empty() && (noduri[n].parent == -1)){
        int nod1 = q.front();
        q.pop();

        for(int poz = noduri[nod1].adj; poz != -1; poz = muchii[poz].next){
            int nod2 = muchii[poz].nod;

            if(noduri[nod2].parent == -1 && muchii[poz].capacitate > 0){
                noduri[nod2].parent = nod1;
                noduri[nod2].edge = poz;
                q.push(nod2);
            }
        }
    }

    return (noduri[n].parent != -1);
}

int path_minimum(){
    int minim = CapMax;
    int nod = n;

    while(nod != 1){
        minim = min(minim, muchii[noduri[nod].edge].capacitate);
        nod = noduri[nod].parent;
    }

    return minim;
}

void pump_on_path(int flow){
    int nod = n;
    while(nod != 1){
        muchii[noduri[nod].edge].capacitate -= flow;
        muchii[noduri[nod].edge ^ 1].capacitate += flow;

        nod = noduri[nod].parent;
    }
}

int ford_fulkerson(){
    int nod, argument;
    long long flow = 0;

    while(can_reach_end_bfs()){
        for(int poz = noduri[n].adj; poz != -1; poz = muchii[poz].next){
            nod = muchii[poz].nod;

            if(nod == 1 || noduri[nod].parent != -1){
                noduri[n].parent = nod;
                noduri[n].edge = poz ^ 1;

                argument = path_minimum();
                if(argument){
                    pump_on_path(argument);
                    flow += argument;
                }
            }
        }
    }

    return flow;
}

int main(){
    citire();

    long long maxflow = ford_fulkerson();
    fout << maxflow;

    return 0;
}