Cod sursa(job #1515413)

Utilizator eu3neuomManghiuc Teodor-Florin eu3neuom Data 1 noiembrie 2015 16:26:35
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMax = 1e3 + 5;

int n;
int Q[NMax];
int C[NMax][NMax], Flow[NMax][NMax], Father[NMax];
bool Used[NMax];

vector < int > G[NMax];

inline bool BFS(){
    vector < int > ::iterator it;
    int node;
    memset(Used, 0, sizeof(Used));
    Q[0] = Q[1] = 1;
    Used[1] = 1;
    for(int i = 1; i <= Q[0]; i++){
        node = Q[i];
        for(it = G[node].begin(); it != G[node].end(); it++){
            if(C[node][*it] != Flow[node][*it] && !Used[*it]){
                Used[*it] = 1;
                Q[++Q[0]] = *it;
                Father[*it] = node;
                if(*it == n) return 1;
            }
        }
    }
    return 0;
}

int main(){
    int m, a, b, c, flowMin, flow;
    vector < int > ::iterator it;
    fin >> n >> m;
    for(int i = 1; i <= m; i++){
        fin >> a >> b >> c;
        C[a][b] += c;
        G[a].push_back(b);
        G[b].push_back(a);
    }
    for(flow = 0; BFS();){
        for(it = G[n].begin(); it != G[n].end(); it++){
            if(C[*it][n] != Flow[*it][n] && Used[*it]){
                Father[n] = *it;
                flowMin = INFINITY;
                for(int node = n; node != 1; node = Father[node]){
                    flowMin = min(flowMin, C[Father[node]][node] - Flow[Father[node]][node]);
                }
                if(flowMin != 0){
                    for(int node = n; node != 1; node = Father[node]){
                        Flow[Father[node]][node] += flowMin;
                        Flow[node][Father[node]] -= flowMin;
                    }
                    flow += flowMin;
                }
            }
        }
    }
    fout << flow;
    return 0;
}