Cod sursa(job #1584997)

Utilizator cristina_borzaCristina Borza cristina_borza Data 30 ianuarie 2016 17:50:47
Problema Flux maxim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>

using namespace std;

ifstream f("maxflow.in");
ofstream g("maxflow.out");

int t[1005] , c[1005][1005] , flow[1005][1005];
int n , m , cost , flux , node1 , node2;

vector <vector <int> > G;

bool bfs();

int main() {
    f >> n >> m;
    G.resize(n + 5);

    for(int i = 1 ; i <= m ; ++i) {
        f >> node1 >> node2 >> cost;
        c[node1][node2] = cost;
        G[node1].push_back(node2);
        G[node2].push_back(node1);
    }

    while(bfs()) {
        int node , val = c[t[n]][n];
        for(node = t[n] ; node != 1 ; node = t[node]) {
            val = min(val , c[t[node]][node] - flow[t[node]][node]);
        }

        for(node = n ; node != 1 ; node = t[node]) {
            flow[t[node]][node] += val;
            flow[node][t[node]] -= val;
        }

        flux += val;
    }

    g << flux;
    return 0;
}

bool bfs() {
    queue <int> q;
    q.push(1);

    memset(t , 0 , sizeof(t));
    t[1] = -1;

    while(!q.empty()) {
        int node = q.front();
        for(vector <int> :: iterator  it = G[node].begin() ; it != G[node].end() ; ++it) {
            if(flow[node][*it] < c[node][*it] && !t[*it]) {
                q.push(*it);
                t[*it] = node;
            }
        }
        q.pop();
    }

    return (t[n] != 0);
}