Cod sursa(job #1585071)

Utilizator cristina_borzaCristina Borza cristina_borza Data 30 ianuarie 2016 18:50:14
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 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()) {
        for(vector <int>::iterator it = G[n].begin() ; it != G[n].end() ; ++it) {
            if(flow[*it][n] < c[*it][n] && t[*it]) {
                int u = *it , val = c[*it][n] - flow[*it][n];
                while(u != 1) {
                    val = min(val , c[t[u]][u] - flow[t[u]][u]);
                    u = t[u];
                }

                u = *it;
                flow[*it][n] += val;
                flow[n][*it] -= val;

                while(u != 1)
                {
                    flow[t[u]][u] += val;
                    flow[u][t[u]] -= val;
                    u = t[u];
                }
                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);
}