Cod sursa(job #2242053)

Utilizator CronosClausCarare Claudiu CronosClaus Data 17 septembrie 2018 17:58:28
Problema Flux maxim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>
#define pp pair<int, int>
#define pb push_back

using namespace std;

const int mxn = 1000 + 10;

vector< pp > g[ mxn ];
int gr[ mxn ][ mxn ];

int d[ mxn ];

int n, m, max_flow;

int s = 1, f;

bool bfs(){
    bitset< mxn > viz;
    queue< int > q;
    q.push( s );
    viz[ s ] = 1;
    d[ s ] = -1;
    int nx;
    while(!q.empty()){
        nx = q.front();
        q.pop();
        for(auto it: g[ nx ]){
            if(viz[ it.first ] == 0 && gr[ nx ][ it.first ] > 0){
                viz[ it.first ] = 1;
                d[ it.first ] = nx;
                q.push( it.first );
            }
        }
    }
    return viz[ f ] == 1;
}

void ford_fulkerson(){
    int mx, u, v;
    while(bfs()){
        mx = INT_MAX;
        u = d[ f ];
        v = f;
        while(u != -1){
            mx = min(mx, gr[ u ][ v ]);
            v = u;
            u = d[ u ];
        }
        u = d[ f ];
        v = f;
        while(u != -1){
            gr[ u ][ v ] -= mx;
            v = u;
            u = d[ u ];
        }
        max_flow += mx;
    }
}

int main()
{
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
    scanf("%d %d", &n, &m);
    f = n;
    for(int i = 1, x, y, z; i <= m; i++){
        scanf("%d %d %d", &x, &y, &z);
        g[ x ].pb(make_pair(y, z));
        gr[ x ][ y ] = z;
    }
    ford_fulkerson();
    printf("%d", max_flow);
    return 0;
}