Cod sursa(job #881617)

Utilizator toranagahVlad Badelita toranagah Data 18 februarie 2013 13:01:20
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <algorithm>
#include <fstream>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;

#define FORIT(it, v) for(typeof((v).begin())it=(v).begin();it!=(v).end();++it)
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

const int MAX_N = 1005;
const int MAX_M = 5005;
const int INF = 1 << 30;

int N, M;
int flux[MAX_N][MAX_N];
vector<int> graph[MAX_N];
bool visited[MAX_N];
int father[MAX_N];
int max_flow = 0;

void read_input();
void solve();
void print_output();
bool dfs(int node);
int get_flow();

int main() {
    read_input();
    solve();
    print_output();
    return 0;
}

void read_input() {
    fin >> N >> M;
    for (int i = 1; i <= M; ++i) {
        int a, b, c;
        fin >> a >> b >> c;
        graph[a].push_back(b);
        graph[b].push_back(a);
        flux[a][b] = c;
    }
}

void solve() {
    while (dfs(1)) {
        max_flow += get_flow();
        fill(father, father + N + 1, 0);
    }
}

void print_output() {
    fout << max_flow;
}

bool dfs(int node) {
    if (node == N) return true;
    FORIT (it, graph[node]) {
        if (!father[*it] && flux[node][*it]) {
            father[*it] = node;
            if (dfs(*it)) return true;
        }
    }
    return false;
}

int get_flow() {
    int result = INF;
    int node = N;
    while (node != 1) {
        result = min(result, flux[father[node]][node]);
        node = father[node];
    }
    node = N;
    while (node != 1) {
        flux[father[node]][node] -= result;
        flux[node][father[node]] += result;
        node = father[node];
    }
    return result;
}