Cod sursa(job #1497388)

Utilizator mucenic_b101Bogdan Mucenic mucenic_b101 Data 6 octombrie 2015 19:07:25
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <set>
#include <vector>
#define MAXN 1000
#define MAXVAL 9999999
using namespace std;

typedef pair <int, int> pere;
typedef queue <pere> coada;
typedef vector <int> lst;
int pre[MAXN + 1];
int z[MAXN + 1][MAXN + 1];
vector <int> G[MAXN + 1];
coada Q;
int n, m, drum, minv;

inline int min(int x, int y) {
    return x < y ? x : y;
}

void bfs(int source) {
    pre[source] = 0;
    Q.push(make_pair(source, MAXVAL));

    while (!Q.empty() && !drum) {
        pere node = Q.front();
        Q.pop();
        if (node.first == n) {
            drum = 1;
            minv = node.second;
        }
        else {

        for (vector <int> :: iterator it = G[node.first].begin() ; it != G[node.first].end() ; ++it)
            if (*it != source && !pre[*it] && z[node.first][*it]) {
                pre[*it] = node.first;
                Q.push(make_pair(*it, min(node.second, z[node.first][*it])));
            }
        }
    }

    while(!Q.empty())
        Q.pop();
}

int main () {
    ifstream cin("maxflow.in");
    ofstream cout("maxflow.out");

    cin >> n >> m;

    for (int i = 0 ; i < m ; ++i) {
        int x, y, zz;
        cin >> x >> y >> zz;

        G[x].push_back(y);
        G[y].push_back(x);
        z[x][y] += zz;
    }

    int maxflow = 0;
    do {
        drum = 0;
        for (int i = 1 ; i <= n ; ++i)
            pre[i] = 0;
        minv = MAXVAL;
        bfs(1);

        if (drum) {
            maxflow += minv;
            int node = n;
            while (pre[node]) {
                z[pre[node]][node] -= minv;
                z[node][pre[node]] += minv;

                node = pre[node];
            }
        }
    } while(drum);

    cout << maxflow << "\n";
    return 0;
}