Cod sursa(job #2699684)

Utilizator raducostacheRadu Costache raducostache Data 25 ianuarie 2021 15:31:45
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 kb
//
//  main.cpp
//  flux
//
//  Created by Radu Costache on 24/01/2021.
//  Copyright © 2021 Radu Costache. All rights reserved.
//

#include <stdio.h>
#include <queue>
#include <vector>

#define NMAX 1005


using namespace std;

int n, m, flow;
int C[NMAX][NMAX], F[NMAX][NMAX], Parent[NMAX];
vector <int> G[NMAX];
bool viz[NMAX] = {0};


int BFS() {
    int i, j;
    memset(viz, 0, sizeof(viz));
    queue<int>q;
    q.push(1);
    viz[1] = 1;
    while (!q.empty()) {
        int currNode = q.front();
        q.pop();
        if (currNode != n)
            for (auto it:G[currNode])
                if (C[currNode][it] != F[currNode][it] && viz[it] == 0) {
                    viz[it] = 1;
                    q.push(it);
                    Parent[it] = currNode;
                }
    }
    return viz[n];
}

int main(int argc, const char * argv[]) {
    // insert code here...
    FILE *f = fopen("maxflow.in", "r");
    FILE *g = fopen("maxflow.out", "w");
    
    fscanf(f, "%d %d\n", &n, &m);
    for (int i = 1; i <= m; ++i) {
        int x, y, z;
        fscanf(f, "%d %d %d\n", &x, &y, &z);
        C[x][y] += z;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    while (BFS()) {
        for (auto it:G[n]) {
            if (F[it][n] != C[it][n] && viz[it]) {
                Parent[n] = it;
                int fmin = C[it][n] - F[it][n];
                for (int node = it; node != 1; node = Parent[node])
                    fmin = min(fmin, C[Parent[node]][node] - F[Parent[node]][node]);
                if(fmin) {
                    flow += fmin;
                    for (int node = n; node != 1; node = Parent[node]) {
                        F[Parent[node]][node] += fmin;
                        F[node][Parent[node]] -= fmin;
                    }
                }
            }
        }
    }
    fprintf(g, "%d\n", flow);
    return 0;
}