Cod sursa(job #1937146)

Utilizator iulian_f2kGuraliuc Iulian iulian_f2k Data 23 martie 2017 19:09:38
Problema Flux maxim Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
#include <iostream>
#include <fstream>
#include <climits>
#include <queue>
using namespace std;

const int NMAX = 1005;
int N, M, Capacity[NMAX][NMAX], Flow[NMAX][NMAX], FLOW;
vector<int> G[NMAX], F;

void Read();
void maxFlow(int source, int dest);
void BFS(int node);
void Write() {  cout << FLOW << '\n';   };

int main()
{
    Read();
    maxFlow(1, N);
    Write();

    return 0;
}
void Read() {
    freopen("maxflow.in", "rt", stdin);     freopen("maxflow.out", "wt", stdout);
    scanf("%d%d", &N, &M);
    while(M--) {
        int a, b, c;    scanf("%d%d%d", &a, &b, &c);
        G[a].push_back(b);
        G[b].push_back(a);
        Capacity[a][b] += c;
    }
    F.assign(N + 1, 0);
}

void maxFlow(int source, int dest) {
    while(true) {
        BFS(1);
        if(F[dest] == 0)     break;             // drumul determinat nu ajunge in destinatie
        for(int i = 0; i < G[dest].size(); i++) {
            int prev = G[dest][i];
            if(Capacity[prev][dest] > Flow[prev][dest] && F[prev]) {
                int mn = INT_MAX;
                for(int node = prev; node != source; node = F[node])
                    mn = min(mn, Capacity[F[node]][node] - Flow[F[node]][node]);
                FLOW += mn;
                Flow[prev][dest] += mn;     Flow[dest][prev] += mn;
                for(int node = prev; node != source; node = F[node])
                    Flow[F[node]][node] += mn,      Flow[node][F[node]] -= mn;
            }
        }

    }
}

void BFS(int node) {
    queue<int> Q;   Q.push(node);
    F.assign(N + 1, 0);     F[node] = -1;
    while(!Q.empty()) {
        node = Q.front();
        Q.pop();
        for(int i = 0; i < G[node].size(); i++) {
            int neigh = G[node][i];
            if(F[neigh] == 0 && Capacity[node][neigh] > Flow[node][neigh]) {
                F[neigh] = node;
                Q.push(neigh);
            }
        }
    }
}