Cod sursa(job #1148466)

Utilizator muresan_bogdanMuresan Bogdan muresan_bogdan Data 20 martie 2014 20:04:31
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;

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

const int MAXN = 1001;
const int INF = 1000000000;

bool viz[MAXN];
int c[MAXN][MAXN], f[MAXN][MAXN], n, m, tata[MAXN], x, y, z, i, flow, fmax;
vector<int> g[MAXN];
queue<int> coada;

bool BFS() {
    memset(viz, 0, sizeof(viz));
    viz[1] = true;
    coada.push(1);
    while(!coada.empty()) {
        int nod = coada.front();
        coada.pop();
        if(nod != n) {
            for(int j = 0; j < g[nod].size(); j++) {
                int v = g[nod][j];
                if(c[nod][v] != f[nod][v] && !viz[v]) {
                    viz[v] = 1;
                    tata[v] = nod;
                    coada.push(v);
                }
            }
        }
    }
    return viz[n];
}

int main() {
    fin >> n >> m;
    for(i = 0; i < m; i++) {
        fin >> x >> y >> z;
        c[x][y] = z;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    flow = 0;
    while(BFS()) {
        for(int j = 0; j < g[n].size(); j++) {
            int v = g[n][j];
            if(c[v][n] != f[v][n] && viz[v]) {
                tata[n] = v;
                fmax = INF;
                v = n;
                while(v != 1) {
                    fmax = min(fmax, c[tata[v]][v] - f[tata[v]][v]);
                    v = tata[v];
                }
                if(fmax != 0) {
                    v = n;
                    while(v != 1) {
                        f[tata[v]][v] += fmax;
                        f[v][tata[v]] -= fmax;
                        v = tata[v];
                    }
                }
                flow += fmax;
            }
        }
    }
    fout << flow << '\n';
    fin.close();
    fout.close();
    return 0;
}