Cod sursa(job #1586413)

Utilizator andrei_diaconuAndrei Diaconu andrei_diaconu Data 1 februarie 2016 09:39:08
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.41 kb
#include <fstream>
#include <vector>
#include <string.h>
#include <queue>
#include <algorithm>

#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, father[NMax], front, back;
vector<int> G[NMax];
bool mark[NMax];
queue<int> QU;

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

void qu_clear(queue<int> &q)
{
   queue<int> mEmpty;
   swap(q, mEmpty);
}

bool BFS(int node)
{
    QU.push(1);
    mark[node] = true;

    while (!QU.empty()) {
        int crtNode = QU.front();
        QU.pop();

        for (vector<int>::iterator it = G[crtNode].begin(); it != G[crtNode].end(); it++) {
            if (!mark[*it] && available(crtNode, *it) > 0) {
                if (*it != t)
                    QU.push(*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));
        qu_clear(QU);

        father[1] = -1;
    }

    g << maxFlow;

    return 0;
}