Cod sursa(job #2126463)

Utilizator andreicoman299Coman Andrei andreicoman299 Data 9 februarie 2018 17:36:47
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>
#define MAXN 1000

int S, D, flux;
std::vector <int> G[1 + MAXN];
int C[1 + MAXN][1 + MAXN], F[1 + MAXN][1 + MAXN];
int father[1 + MAXN];
int q[1 + MAXN], p, u;

inline bool bfs(){
    memset(father, 0, sizeof(father));
    p = 0, u = 1;
    q[0] = S;
    while(p != u){
        int node = q[p++];
        for(auto y:G[node])
            if(!father[y] && C[node][y] != F[node][y]) father[y] = node, q[u++] = y;
        if(father[D]) return 1;
    }
    return 0;
}

int main(){
    FILE*fi,*fo;
    fi = fopen("maxflow.in","r");
    fo = fopen("maxflow.out","w");

    int n, m;
    fscanf(fi,"%d%d", &n, &m);
    for(int i = 1; i <= m; i++){
        int x, y, z;
        fscanf(fi,"%d%d%d", &x, &y, &z);
        G[x].push_back(y);
        G[y].push_back(x);
        C[x][y] += z;
    }

    S = 1, D = n;
    while(bfs())
        for(auto y:G[D])
            if(father[y] && C[y][D] != F[y][D]){
                father[D] = y;
                int flow = 1000000000;
                for(int i = D; i != S; i = father[i]) flow = std::min(flow, C[father[i]][i] - F[father[i]][i]);
                if(flow){
                    for(int i = D; i != S; i = father[i]) F[father[i]][i] += flow, F[i][father[i]] -= flow;
                    flux += flow;
                }
            }
    fprintf(fo,"%d", flux);
    return 0;
}