Cod sursa(job #2422011)

Utilizator razvanlgu31Razvan Lungu razvanlgu31 Data 16 mai 2019 21:39:53
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>
#include <bits/stdc++.h>
#define inf 0x3f3f3f3f


using namespace std;

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

int n, m, c[1010][1010], s, d, cost, par[1010], viz[1010];
vector <int> v[1010];

int bfs() {
    queue <int> q;
//    for (int i = 0; i <= n; i++) {
//        viz[i] = 0;
//    }
    memset(viz, 0, sizeof(viz));
    q.push(1);
    viz[1] = 1;

    while(!q.empty()) {
        int nod = q.front();
        q.pop();

        for (int i = 0; i < v[nod].size(); i++) {
            int u = v[nod][i];
            if (viz[u] == 0 && c[nod][u] > 0) {
                viz[u] = 1;
                par[u] = nod;
                q.push(u);
            }
        }
    }
    return viz[n];
}

int main()
{
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        fin >> s >> d >> cost;
        c[s][d] = cost;
        v[s].push_back(d);
        v[d].push_back(s);
    }

    int flow = 0;
//    bfs();
    while (bfs()) {
        for (int i = 0; i < v[n].size(); i++) {
            int u = v[n][i];
            if (c[u][n] > 0) {
                par[n] = u;
                int cflow = inf;
                for (int nod = n; nod != 1; nod = par[nod]) {
                    cflow = min(cflow, c[par[nod]][nod]);
                }

                if (cflow == 0) {
                    continue;
                }

                for (int nod = n; nod != 1; nod = par[nod]) {
                    c[par[nod]][nod] -= cflow;
                    c[nod][par[nod]] += cflow;
                }
                flow += cflow;
            }
        }
    }


    fout << flow;


    return 0;
}