Cod sursa(job #2076767)

Utilizator seby0007Pop Sebastian seby0007 Data 27 noiembrie 2017 03:09:21
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <bits/stdc++.h>

#define NN 1005
#define oo 0x3f3f3f3
using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int N, M, ffmin;
int cap[NN][NN], flux[NN][NN];
bitset<NN>discovered(false);
vector<vector<int>>G;
vector<int>father;

void readGraph(){

    fin >> N >> M;
    father.resize(N + 1, 0);
    G.resize(N + 1, vector<int>());
    for (int i = 1, x, y, z; i <= M; ++i)
    {
        fin >> x >> y >> z;
        cap[x][y] += z;
        G[x].push_back(y);
        G[y].push_back(x);
    }
}

bool BFS(int nod)
{
    queue<int> Q;
    father.resize(N + 1, 0);
    discovered.reset();
    Q.push(nod);
    discovered[nod] = true;
    while(!Q.empty()){
        int k = Q.front(); Q.pop();
        if (k == N)
            continue;
        for (auto x : G[k])
            if (!discovered[x] && cap[k][x] - flux[k][x] > 0)
            {
                Q.push(x);
                discovered[x] = true;
                father[x] = k;
            }
    }
    return discovered[N];
}

int main()
{
    readGraph();
    int flow;
    for (flow = 0; BFS(1); ){
        for (auto x : G[N])
        {
            father[N] = x;
            ffmin = oo;
            for (int nod = N; father[nod]; nod = father[nod])
                ffmin = min(ffmin, cap[father[nod]][nod] - flux[father[nod]][nod]);

            if (!ffmin)
                continue;

            for (int nod = N; father[nod]; nod = father[nod])
            {
                flux[father[nod]][nod] += ffmin;
                flux[nod][father[nod]] -= ffmin;
            }
            flow += ffmin;
        }
    }

    fout << flow;

    return 0;
}