Cod sursa(job #2591201)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 29 martie 2020 23:25:52
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <bits/stdc++.h>
 
using namespace std;
 
int N, M;
const int Nmax = 1005;
int capacity[Nmax][Nmax];
int flow[Nmax][Nmax];
int daddy[Nmax];
 
int start, sink;
const int INF = 0x3f3f3f3f;
vector<int> G[Nmax];
 
void readNetwork()
{
    cin >> N >> M;
    for(int i = 1; i <= M; ++i) {
        int a,b,c;
        cin >> a >> b >> c;
        G[a].push_back(b);
        G[b].push_back(a);
        capacity[a][b] = c;
    }
    start = 1;
    sink = N;
}
 
bool BFS(int k)
{
    bitset<Nmax>used;
    queue<int> Q;
    Q.push(k);
    used[k] = true;
    while(!Q.empty())
    {
        k = Q.front(); Q.pop();
        if(k == sink)
            continue;
        for(auto it : G[k])
            if(!used[it] && capacity[k][it] - flow[k][it] > 0) {
                used[it] = true;
                daddy[it] = k;
                Q.push(it);
            }
    }
    return used[N];
}
 
void maxFlow()
{
    int mFlow = 0;
    while(BFS(start))
    for(auto it : G[sink]) {
        daddy[sink] = it;
        if(capacity[it][sink] == flow[it][sink])
            continue;
 
        int bottleNeck = INF;
        for(int k = sink; k != start; k = daddy[k])
            bottleNeck = min(bottleNeck, capacity[daddy[k]][k] - flow[daddy[k]][k]);
 
        for(int k = sink; k != start; k = daddy[k]) {
            flow[daddy[k]][k] += bottleNeck;
            flow[k][daddy[k]] -= bottleNeck;
        }
 
        mFlow += bottleNeck;
    }
    cout << mFlow << "\n";
}
 
int main()
{
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
 
    ios::sync_with_stdio(false);
 
    readNetwork();
    maxFlow();
 
 
    return 0;
}