Cod sursa(job #1519967)

Utilizator andrei_diaconuAndrei Diaconu andrei_diaconu Data 8 noiembrie 2015 10:36:38
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.29 kb
#include <fstream>
#include <vector>
#include <string.h>

#define NMax 1010
#define INF 2000000000

using namespace std;

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

int nodes, edges, flow[NMax][NMax], capacity[NMax][NMax], maxFlow, qu[NMax], father[NMax], front, back;
vector<int> G[NMax];
bool mark[NMax];

int available(int node1, int node2)
{
    return capacity[node1][node2] - flow[node1][node2];
}


bool BFS(int node)
{
    int front = 1, back = 1;
    qu[back] = 1;
    mark[node] = true;

    while (front <= back) {
        int crtNode = qu[front];
        front++;

        for (vector<int>::iterator it = G[crtNode].begin(); it != G[crtNode].end(); it++) {
            if (!mark[*it] && available(crtNode, *it) > 0) {
                back++;
                qu[back] = *it;

                father[*it] = crtNode;
                mark[*it] = true;
            }
        }
    }

    return mark[nodes];
}

int main()
{
    f>>nodes>>edges;

    int node1, node2, cap;
    for (int i=1; i<=edges; i++) {
        f>>node1>>node2>>cap;

        G[node1].push_back(node2);
        G[node2].push_back(node1);

        capacity[node1][node2] = cap;
    }

    while (BFS(1)) {
        for (vector<int>::iterator it = G[nodes].begin(); it != G[nodes].end(); it++) {
            if (available(*it, nodes) > 0) {
                int crtNode, crtFlow = available(*it, nodes);

                crtNode = *it;
                while (father[crtNode] > 0) {
                    if (crtFlow > available(father[crtNode], crtNode))
                        crtFlow = available(father[crtNode], crtNode);

                   crtNode = father[crtNode];
                }

                flow[*it][nodes] += crtFlow;
                flow[nodes][*it] -= crtFlow;

                crtNode = *it;
                while (father[crtNode] > 0) {
                    flow[father[crtNode]][crtNode] += crtFlow;
                    flow[crtNode][father[crtNode]] -= crtFlow;

                    crtNode = father[crtNode];
                }

                maxFlow += crtFlow;
            }
        }

        memset(mark, 0, sizeof (mark));
        memset(father, 0, sizeof (father));
        father[1] = -1;
    }

    g << maxFlow;

    return 0;
}