Cod sursa(job #2188236)

Utilizator flaviu_2001Craciun Ioan-Flaviu flaviu_2001 Data 27 martie 2018 00:19:42
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>

using namespace std;

const string fisier = "maxflow";
const int nmax = 1005;
int n, m, c[nmax][nmax], d[nmax][nmax], f[nmax][nmax], prv[nmax];
bool ok[nmax];
vector<int> v[nmax];

bool bfs()
{
    queue<int> q;
    q.push(1);
    memset(ok, 0, sizeof(ok));
    ok[1] = 1;
    while(!q.empty()){
        int k = q.front();
        q.pop();
        for (vector<int>::iterator it = v[k].begin(); it != v[k].end(); ++it)
            if(!ok[*it] && f[k][*it] < c[k][*it]){
                ok[*it] = 1;
                prv[*it] = k;
                q.push(*it);
                if(*it == n)
                    return true;
            }
    }
    return false;
}

int main()
{
    ifstream fin (fisier+".in");
    ofstream fout (fisier+".out");
    fin >> n >> m;
    for (int i = 1; i <= m; ++i){
        int x, y, z;
        fin >> x >> y >> z;
        v[x].push_back(y);
        v[y].push_back(x);
        c[x][y] = z;
    }
    int flow = 0;
    while(bfs())
        for (vector<int>::iterator it = v[n].begin(); it != v[n].end(); ++it)
            if(ok[*it]){
                prv[n] = *it;
                int mn = 2000000000, k = n;
                while(k != 1){
                    mn = min(mn, c[prv[k]][k]-f[prv[k]][k]);
                    k = prv[k];
                }
                if(mn == 0)
                    continue;
                flow += mn;
                k = n;
                while(k != 1){
                    f[prv[k]][k] += mn;
                    f[k][prv[k]] -= mn;
                    k = prv[k];
                }
            }
    fout << flow << "\n";
    return 0;
}