Cod sursa(job #1600459)

Utilizator TeodorCotetCotet Teodor TeodorCotet Data 15 februarie 2016 03:30:40
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.02 kb
#include <fstream>
#include <iostream>
#include <queue>
#include <vector>
#include <bitset>

using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

const int NMAX = 1000;
const int MMAX = 5000;
const int INF = 0x7fffffff;

int n; int m;

vector< vector<int> > g(NMAX + 1, vector<int>(0));

int capacity[NMAX + 1][NMAX + 1];
int flow[NMAX + 1][NMAX + 1];

vector<int> previous(NMAX + 1);

int solution;

void read() {

    fin >> n >> m;

    for(int i = 1; i <= m ;++i) {

        int x; int y; int cap;
        fin >> x >> y >> cap;
        capacity[x][y] = cap;
        g[x].push_back(y);
        g[y].push_back(x);
    }
}

bool findPaths(int start, int dest, vector< vector<int> >& g) {

    queue<int> q;
    bitset<NMAX + 1> vis;

    q.push(start);
    vis[start] = true;
    previous[start] = start;

    while(q.empty() == false) {

        int node = q.front();
        q.pop();

        for(int x : g[node]) {
            if(vis[x] == false && capacity[node][x] > flow[node][x]) {

                vis[x] = true;

                if(x == n) continue;

                q.push(x);
                previous[x] = node;
            }
        }
    }
    return vis[dest];
}

void solve(int start, int dest, vector< vector<int> >& g) {

    while(findPaths(start, dest, g)) {

        for(int x : g[dest]) {

            int maxFlow = INF;

            previous[dest] = x;
            x = dest;

            while(previous[x] != x) {
                maxFlow = min(maxFlow, capacity[previous[x]][x] - flow[previous[x]][x]);
                x = previous[x];
            }

            x = dest;

            while(previous[x] != x) {
                flow[previous[x]][x] += maxFlow;
                flow[x][previous[x]] -= maxFlow;
                x = previous[x];
            }

            solution += maxFlow;
        }
    }
}

int main() {

    read();

    solve(1, n, g);

    fout << solution << '\n';

    return 0;
}