Cod sursa(job #1213778)

Utilizator abel1090Abel Putovits abel1090 Data 28 iulie 2014 22:55:27
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.39 kb
///MAXFLOW
#include <iostream>
#include <fstream>
#include <vector>
#include <limits>
#include <queue>
#include <list>

using namespace std;

const unsigned INF = numeric_limits<unsigned>::max();

unsigned getAugmentedPath(vector<list<short> >& adjList,  ///BFS
                vector<vector<unsigned> >& capacity) {
    unsigned augmentedPath = INF;
    short sink = adjList.size() - 1;
    vector<bool> seen(sink + 1, false);
    vector<short> previous(sink + 1, -1);
    queue<short> q;
    seen[0] = true;

    q.push(0);
    list<short>::iterator it;
    short current;
    while(!q.empty()) {
        current = q.front();
        q.pop();

        if(current == sink)
            break;

        for(it = adjList[current].begin(); it != adjList[current].end(); it++)
            if(!seen[*it] && capacity[current][*it] > 0) {
                seen[*it] = true;
                previous[*it] = current;
                q.push(*it);
            }
    }

    short from;
    while(previous[sink] > -1) {
        from = previous[sink];
        if(capacity[from][sink] < augmentedPath)
            augmentedPath = capacity[from][sink];
        sink = from;
    }

    sink = adjList.size() - 1;
    while(previous[sink] > -1) {
        from = previous[sink];
        capacity[from][sink] -= augmentedPath;
        capacity[sink][from] += augmentedPath;
        sink = from;
    }

    if(augmentedPath == INF)
        return 0;

    return augmentedPath;
}

unsigned getMaxFlow(vector<list<short> >& adjList,
                vector<vector<unsigned> >& capacity) {
    unsigned maxFlow = 0, newPath;

    while(true) {
        newPath = getAugmentedPath(adjList, capacity);
        if(newPath == 0)
            break;
        maxFlow += newPath;
    }

    return maxFlow;
}

int main() {
    ifstream inStr("maxflow.in");
    ofstream outStr("maxflow.out");

    short numNodes, numEdges;

    inStr >> numNodes >> numEdges;

    vector<vector<unsigned> > capacity(numNodes, vector<unsigned>(numNodes, 0));
    vector<list<short> > adjList(numNodes);

    short from, to;
    unsigned cap;
    for(short i=0; i < numEdges; i++) {
        inStr >> from >> to >> cap;
        adjList[--from].push_back(--to);
        adjList[to].push_back(from);
        capacity[from][to] = cap;
    }

    cout << getMaxFlow(adjList, capacity) << '\n';

    return 0;
}