Cod sursa(job #2381445)

Utilizator greelioGreenio Greely greelio Data 16 martie 2019 19:40:12
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include<bits/stdc++.h>
#define N 1010
using namespace std;

const int inf=1e9;
int n,m, rs;
int viz[N];
int a[N][N];
vector<int>V[N];
queue<int>Q;

bool BFS(int x) {
    Q.push(x);
    for (int i=2; i<=n; ++i) viz[i]=-1;
    while (Q.size()) {
        x=Q.front(); Q.pop();
        for (auto it:V[x]) {
            if (viz[it]==-1 && a[x][it]>0) {
                Q.push(it);
                viz[it]=x;
            }
        }
    }
    return (viz[n]!=-1);
}

int main() {
    ifstream cin("maxflow.in");
    ofstream cout("maxflow.out");
    cin>>n>>m;
    for (int i=1; i<=m; ++i) {
        int x,y,c; cin>>x>>y>>c;
        V[x].push_back(y);
        V[y].push_back(x);
        a[x][y]+=c;
    }
    while (BFS(1)) {
        for (auto it:V[n]) {
            if (viz[it]==-1 || !a[it][n]) continue;
            int flow=a[it][n];
            for (int i=it; viz[i]; i=viz[i]) {
                flow=min(flow, a[viz[i]][i]);
            }
            rs+=flow;
            a[it][n]-=flow; //!!!
            a[n][it]+=flow;
            for (int i=it; viz[i]; i=viz[i]) {
                a[viz[i]][i]-=flow;
                a[i][viz[i]]+=flow;
            }
        }
    }
    cout<<rs;


    return 0;
}