Cod sursa(job #1489003)

Utilizator diana97Diana Ghinea diana97 Data 20 septembrie 2015 13:02:18
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.45 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>

using namespace std;

ifstream f ("maxflow.in");
ofstream g ("maxflow.out");

const int MAX_NODES_COUNT = 1000;
const int MAX_EDGES_COUNT = 5000;
const int INF = (1 << 30);

int nodes_count, edges_count;
int source, destination;


int father[MAX_NODES_COUNT];
int visited[MAX_NODES_COUNT];

vector <int> graph[MAX_NODES_COUNT];

int capacity[MAX_NODES_COUNT][MAX_NODES_COUNT];
int flow[MAX_NODES_COUNT][MAX_NODES_COUNT];

void read() {
    int node1, node2, current_capacity;

    f >> nodes_count >> edges_count;

    for (int i = 1; i <= edges_count; ++i) {
        f >> node1 >> node2 >> current_capacity;
        capacity[node1][node2] += current_capacity;
        graph[node1].push_back(node2);
        graph[node2].push_back(node1);
    }
}

bool BFS() {
    int node, son, sons_count;
    queue <int> Q;

    for (int i = 1; i <= nodes_count; ++i)
        visited[i] = false;

    Q.push(source);
    visited[source] = true;

    while(!Q.empty()) {
        node = Q.front();
        Q.pop();
        if (node == destination)
            break;
        sons_count = graph[node].size();
        for (int i = 0; i < sons_count; ++i) {
            son = graph[node][i];
            if (!visited[son] && flow[node][son] < capacity[node][son]) {
                visited[son] = true;
                Q.push(son);
                father[son] = node;
            }
        }
    }
    return visited[destination];
}

int max_flow() {
    int sons_count, node, ant, minim, sol;

    sol = 0;

    while (BFS()) {
        sons_count = graph[destination].size();
        for (int i = 0; i < sons_count; ++i) {
            node = graph[destination][i];

            if (capacity[node][destination] <= flow[node][destination] || !visited[node]) continue;

            father[destination] = node; node = destination;
            minim = INF;
            while (node != source) {
                ant = father[node];
                minim = min(minim, capacity[ant][node] - flow[ant][node]);
                node = ant;
            }
            node = destination;
            while (node != source) {
                ant = father[node];
                flow[node][ant] -= minim;
                flow[ant][node] += minim;
                node = ant;
            }
            sol += minim;
        }
    }

    return sol;
}

int main() {
    read();
    source = 1;
    destination = nodes_count;
    g << max_flow() << '\n';
    return 0;
}