Cod sursa(job #2192985)

Utilizator DenisONIcBanu Denis Andrei DenisONIc Data 7 aprilie 2018 23:11:29
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>
#define pii pair<int,int>
#define Nmax 1005
using namespace std;

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

int n,m,S = 1,D,x,y,c,ans;
vector<pii> E;
vector<int> v[Nmax],G[Nmax],H;
int uz[Nmax],viz[Nmax];

bool bfs(){
    memset(uz,0,sizeof(uz));
    H.clear();
    H.push_back(S);
    for (int i=1; i<=n; i++) G[i].clear();
    for (int i=0; i<H.size(); i++){
        if (H[i]==D) return 1;
        for (auto it : v[H[i]]){
            if (!E[it].second) continue;
            if (uz[E[it].first]==0){
                uz[E[it].first] = uz[H[i]]+1;
                H.push_back(E[it].first);
            }
            if (uz[E[it].first]==uz[H[i]]+1) G[H[i]].push_back(it);
        }
    }
    return 0;
}

int dfs(int nod,int flow){
    viz[nod] = 1;
    int crtF = 0;
    if (nod==D || !flow){
        viz[nod] = 0;
        return flow;
    }
    for (auto it : G[nod]){
        if (viz[E[it].first]) continue;
        int aux = dfs(E[it].first,min(flow-crtF,E[it].second));
        crtF += aux;
        E[it].second -= aux;
        E[it^1].second += aux;
    }
    viz[nod] = 0;
    return crtF;
}

int main()
{
    f>>n>>m;
    D = n;
    for (int i=1; i<=m; i++){
        f>>x>>y>>c;
        v[x].push_back(E.size());
        E.push_back({y,c});
        v[y].push_back(E.size());
        E.push_back({x,0});
    }

    while (bfs()) ans += dfs(S,2e9);

    g<<ans;

    return 0;
}