Cod sursa(job #2064216)

Utilizator StarGold2Emanuel Nrx StarGold2 Data 11 noiembrie 2017 23:25:41
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <bits/stdc++.h>
using namespace std;

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

const int NMAX = 1005;
const int INF = 0x3f3f3f3f;

deque<int> que; int dst[NMAX];
int lst[NMAX][NMAX], aux[NMAX][NMAX], cap[NMAX][NMAX];

inline void addEdge(int x, int y, int f)
{
    lst[x][++lst[x][0]] = y;
    cap[x][y] = f;
}

void bfs(int s, int d)
{
    memset(dst, INF, (d + 1) << 2);
    que.assign(1, s); dst[s] = 0;
    
    for (; que.size(); que.pop_front()) {
        int x = que.front(); aux[x][0] = 0;
        
        if (x == d)
            continue;
        
        for (int i = 1; i <= lst[x][0]; ++i) {
            int y = lst[x][i];
            
            if (!cap[x][y])
                continue;
            if (dst[y] == INF)
                que.push_back(y);
            
            if (dst[y] >= dst[x] + 1) {
                dst[y] = dst[x] + 1;
                aux[x][++aux[x][0]] = y;
            }
        }
    }
}

int dfs(int x, int d, int mxf)
{
    if (mxf == 0) return 0;
    if (x == d) return mxf;
    
    int flo = 0;
    for (int i = 1; i <= aux[x][0]; ++i) {
        int y = aux[x][i];
        
        int val = dfs(y, d, min(cap[x][y], mxf - flo));
        cap[x][y] -= val; cap[y][x] += val; flo += val;
    }
    
    return flo;
}

int main(void)
{
    int n, m;
    in >> n >> m;
    
    for (int i = 1; i <= m; ++i) {
        int x, y, f;
        in >> x >> y >> f;
        
        addEdge(x, y, f);
        addEdge(y, x, f);
    }
    
    int x, ans = 0;
    do {
        bfs(1, n);
        x = dfs(1, n, INF); ans += x;
    } while (x);
    
    out << ans << endl;
    return 0;
}