Cod sursa(job #1345583)

Utilizator somuBanil Ardej somu Data 17 februarie 2015 19:01:36
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.17 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define nmax 1010

using namespace std;

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

int n, m, S, D, fluxMax;
int capacitate[nmax][nmax], flux[nmax][nmax];
int tata[nmax];
vector <int> G[nmax];

void read() {
    int x, y;
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        fin >> x >> y >> capacitate[x][y];
        G[x].push_back(y);
        G[y].push_back(x);
    }
}

bool bfs() {
    
    bool ok = false;
    
    queue <int> q;
    memset(tata, 0, sizeof(tata));
    
    q.push(S);
    tata[S] = -1;
    
    while (!q.empty()) {
        
        int nod = q.front(); q.pop();
        
        for (int i = 0 ; i < G[nod].size(); i++) {
            int vecin = G[nod][i];
            
            if (capacitate[nod][vecin] > flux[nod][vecin] && tata[vecin] == 0) {
                if (vecin != D) {
                    tata[vecin] = nod;
                    q.push(vecin);
                }
                ok = true;
            }
        }
        
    }
    
    return ok;
}

void solve() {
 
    S = 1, D = n;
    
    while (bfs()) {
        
        for (int i = 0; i < G[D].size(); i++) {
            int vecin = G[D][i];
            
            if (tata[vecin] != 0 && capacitate[vecin][D] > flux[vecin][D]) {
                
                tata[D] = vecin;
                
                int Min = 110005;
                
                int nod = D;
                while (nod != S) {
                    Min = min(Min, capacitate[tata[nod]][nod] - flux[tata[nod]][nod]);
                    nod = tata[nod];
                }
                
                if (Min == 0) continue;
                
                fluxMax += Min;
                
                nod = D;
                while (nod != S) {
                    flux[tata[nod]][nod] += Min;
                    flux[nod][tata[nod]] -= Min;
                    nod = tata[nod];
                }
                
            }
            
        }
        
    }
    
    fout << fluxMax << "\n";
    
}

int main() {
    
    read();
    solve();
    
    fin.close();
    fout.close();
    
    return 0;
}