Cod sursa(job #2492645)

Utilizator AlexBolfaAlex Bolfa AlexBolfa Data 15 noiembrie 2019 08:59:42
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <bits/stdc++.h>
#define NMAX (int)(1e3+4)
#define pb push_back
#define ft first
#define sd second
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
typedef pair <int, int> pairINT;
typedef long long ll;

int n,cap[NMAX][NMAX],flow[NMAX][NMAX],t[NMAX];
vector <int> g[NMAX];
queue <int> q;

int maxFlow();
bool bfs(int);

int main(){
    int m,x,y,c;
    fin>>n>>m;
    for(int i=0;i<m;++i){
        fin>>x>>y>>c;
        cap[x][y]=c;
        g[x].pb(y);
        g[y].pb(x);
    }
    fout<<maxFlow();
    return 0;
}
bool bfs(int node){
    bool ok=0;
    memset(t, 0, sizeof t);
    q.push(node);
    while(!q.empty()){
        node=q.front(); q.pop();
        for(auto to:g[node]){
            if(!t[to] && cap[node][to] != flow[node][to]){
                if(to != n){
                    q.push(to);
                    t[to]=node;
                }
                else ok=1;
            }
        }
    }
    return ok;
}
int maxFlow(){
    int node,p,add, mxflow=0;
    while(bfs(1)){
        for(auto to:g[n]){
            if(t[to]){
                node=to;
                add=cap[to][n] - flow[to][n];
                while(node!=1){
                    p=t[node];
                    add=min(add, cap[p][node] - flow[p][node]);
                    node=t[node];
                }
                mxflow+=add;
                flow[to][n]+=add;
                flow[n][to]-=add;
                node=to;
                while(node!=1){
                    p=t[node];
                    flow[p][node]+=add;
                    flow[node][p]-=add;
                    node=t[node];
                }
            }
        }
    }
    return mxflow;
}