Cod sursa(job #2689821)

Utilizator AvramDanielAvram Daniel AvramDaniel Data 22 decembrie 2020 12:56:18
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include<bits/stdc++.h>
using namespace std;

#define N 1001
#define fi first
#define se second
#define INF 110000

int adj[N][N];
int n;
vector< pair<int,int> > path;
vector<int> v[N];
void graph(int _n){
    n = _n;
    for(int i = 1;i<=n;i++)
        for(int j = 1;j<=n;j++)
            adj[i][j] = 0;
    path = vector< pair<int,int> >(n+1, {0,0});
}

void bfs(){
    queue<int> q;
    path = vector< pair<int,int> >(n+1, {0,0});
    q.push(1);
    path[1] = {-1, INF};
    while(!q.empty()){
        int curr = q.front();
        q.pop();
        for(auto j: v[curr]){
            if(adj[curr][j]){
                if(!path[j].fi && path[j].fi != 1){
                    path[j].fi = curr;
                    path[j].se = min(path[curr].se, adj[curr][j]);
                    q.push(j);
                }
            }
        }
    }
}

int maxflow(){
    int ans = 0;
    while(true){
        bfs();
        if(path[n].fi == 0)
            return ans;
        else{
            int curr = n;
            int flow = path[n].se;
            while(path[curr].fi != -1){
                adj[path[curr].fi][curr] -= flow;
                adj[curr][path[curr].fi] += flow;
                curr = path[curr].fi;
            }
            ans += flow;
        }


    }
}


int main(){

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

    int m,n;
    cin>>n>>m;
    graph(n);

    for(int i = 0;i<m;i++){
        int a,b,c;
        cin>>a>>b>>c;
        adj[a][b] = c;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    cout<<maxflow();

    return 0;
}