Cod sursa(job #1690308)

Utilizator tudormaximTudor Maxim tudormaxim Data 14 aprilie 2016 23:09:35
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
using namespace std;

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

const int nmax = 1005;
const int oo = 1<<30;
vector <int> g[nmax];
bitset <nmax> viz;
int c[nmax][nmax], f[nmax][nmax], dady[nmax];

inline bool bfs(int source, int dest) {
    queue <int> q;
    int dad;
    viz=0;
    q.push(source);
    viz[source]=true;
    while(!q.empty()) {
        dad=q.front();
        q.pop();
        for(auto son : g[dad]) {
            if(viz[son]==false && c[dad][son] > f[dad][son]) {
                viz[son]=true;
                dady[son]=dad;
                viz[son]=true;
                q.push(son);
            }
        }
    }
    return viz[dest];
}

void Edmunson_Karp(int source, int dest) {
    int flow, maxflow=0, i, nod;
    while(bfs(source, dest)) {
        for(auto dad : g[dest]) {
            if(viz[dad]==true && c[dad][dest] > f[dad][dest]) {
                flow=oo;
                for(nod=dest; nod!=source; nod=dady[nod])
                    flow=min(flow, c[dady[nod]][nod]-f[dady[nod]][nod]);
                maxflow+=flow;
                for(nod=dest; nod!=source; nod=dady[nod]) {
                    f[dady[nod]][nod]+=flow;
                    f[nod][dady[nod]]-=flow;
                }

            }
        }

    }
    fout << maxflow << "\n";
}

int main() {
    ios_base::sync_with_stdio(false);
    int n, m, x, y, cap, i;
    fin >> n >> m;
    for(i=1; i<=m; i++) {
        fin >> x >> y >> cap;
        c[x][y]=cap;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    Edmunson_Karp(1, n);
    return 0;
}