Cod sursa(job #1393440)

Utilizator rootsroots1 roots Data 19 martie 2015 14:06:13
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 kb
#include <stdio.h>
#include <vector>
#include <queue>

#define MAXN 1001

using namespace std;

int V, E;
vector <int> Gf[MAXN];
int c[MAXN][MAXN];
int s, t;
int f1[MAXN][MAXN];
int father[MAXN];

inline void readAndBuild() {
    scanf("%d%d", &V, &E);
    s = 1;
    t = V;
    
    int x, y, z;
    for (int e = 0; e < E; ++ e) {
        scanf("%d%d%d", &x, &y, &z);
        
        if (c[y][x] == 0) {
            Gf[x].push_back(y);
            c[x][y] = z;
            
            Gf[y].push_back(x);
        } else {
            c[x][y] = z;
        }
    }
}

inline bool bfs() {
    queue <int> q;
    q.push(s);
    
    for (int i = 1; i <= V; ++ i) {
        father[i] = 0;
    }
    
    for (int node = q.front(); !q.empty(); node = q.front()) {
        q.pop();
        
        if (node == t) {
            return true;
        }
        
        for (vector <int>::iterator it = Gf[node].begin(); it != Gf[node].end(); ++ it) {
            if (!father[*it] && f1[node][*it] < c[node][*it]) {
                father[*it] = node;
                q.push(*it);
            }
        }
    }
    
    return false;
}

inline int maxFlowEdmondsKarpWithHacks() {
    int maxFlow = 0;
    
    for (int isPath = bfs(); isPath; isPath = bfs()) {
        int cfpath = c[father[t]][t] - f1[father[t]][t];
        
        for (int node = father[t]; node != s; node = father[node]) {
            if (cfpath > c[father[node]][node] - f1[father[node]][node]) {
                cfpath = c[father[node]][node] - f1[father[node]][node];
            }
        }
        
        maxFlow += cfpath;
        
        for (int node = t; node != s; node = father[node]) {
            f1[father[node]][node] += cfpath;
            f1[node][father[node]] -= cfpath;
        }
    }
    
    return maxFlow;
}

int main() {
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
    
    readAndBuild();
    int F = maxFlowEdmondsKarpWithHacks();
    printf("%d\n", F);
    
    return 0;
}