Cod sursa(job #2956086)

Utilizator tudorcomanTudor Coman tudorcoman Data 18 decembrie 2022 16:07:46
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.17 kb

#include <fstream>
#include <queue>

using namespace std;

const int maxN = 1024; 
const int infi = 1 << 30;

struct Muchie {
    int src, dest;
    int flx, cap; 
    Muchie (int _src = 0, int _dest = 0, int _flx = 0, int _cap = 0):
        src(_src), dest(_dest), flx(_flx), cap(_cap) { }
} father[maxN];

vector<Muchie> G[maxN];
int cost[maxN];

void clear(int N) {
    for (int i = 1; i <= N; i ++) {
        cost[i] = infi;
        father[i] = Muchie();
    }
}

bool bfs(int N) {
    clear(N);
    queue<int> q;
    cost[1] = 0; q.push(1);
    while(!q.empty()) {
        int top = q.front(); q.pop();
        for (auto it: G[top]) {
            if (cost[top] + 1 < cost[it.dest] && it.flx < it.cap) {
                cost[it.dest] = cost[top] + 1;
                father[it.dest] = it; 
                q.push(it.dest); 
            }
        }
    }
    return cost[N] != infi; 
}


int main() {
    ifstream in("maxflow.in");
    ofstream out("maxflow.out");
    int N, M;
    in >> N >> M; 

    for (int i = 1; i <= M; i ++) {
        int src, dest, cap;
        in >> src >> dest >> cap;
        G[src].push_back(Muchie(src, dest, 0, cap));
        G[dest].push_back(Muchie(dest, src, 0, 0));
    }

    while(bfs(N)) {
        vector<Muchie> drum; 
        int x = N;
        while(father[x].src) {
            drum.push_back(father[x]);
            x = father[x].src; 
        }

        int max_flow = infi;
        for (auto it: drum)
            max_flow = min(max_flow, it.cap - it.flx);

        for (auto edge: drum) {
            bool found = false;

            for (int i = 0; i < (int)G[edge.src].size() && !found; i ++) {
                if (G[edge.src][i].dest == edge.dest) {
                    G[edge.src][i].flx += max_flow;
                    found = true;
                }
            }

            found = false;
            for (int i = 0; i < (int)G[edge.dest].size() && !found; i ++) {
                if (G[edge.dest][i].dest == edge.src) {
                    G[edge.dest][i].flx -= max_flow; 
                    found = true;
                }
            }
        }
    }

    int flux = 0;
    for (auto it: G[1])
        flux += it.flx;

    out << flux << '\n'; 
    return 0;
}