Cod sursa(job #2696879)

Utilizator dariahazaparuHazaparu Daria dariahazaparu Data 17 ianuarie 2021 01:00:39
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

const int N_MAX = 10005;
const int INF = 1e9;

std :: vector <int> graph[N_MAX];
int rest[N_MAX][N_MAX], next[N_MAX];
bool vis[N_MAX];
std :: queue<int> q;
int n, m, maxflow;


bool bfs(int i);

int main() {
    std :: ifstream fin("maxflow.in");
    std :: ofstream fout("maxflow.out");

    fin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int a, b, c;
        fin >> a >> b >> c;
        graph[a].push_back(b);
        graph[b].push_back(a);
        rest[a][b] = c;
    }
    while(bfs(1)) {
        for (auto i : graph[n]) {
            if (vis[i] and rest[i][n]) {
                int x = INF;
                next[n] = i;
                for (int j = n; j != 1; j = next[j]) {
                    x = std :: min(x, rest[next[j]][j]);
                }
                for (int j = n; j != 1; j = next[j]) {
                    rest[next[j]][j] -= x;
                    rest[j][next[j]] += x;
                }
                maxflow += x;
            }
        }
    }
    fout << maxflow;
   return 0;
}

bool bfs(int x) {

    for (int i = 1; i <= n; ++i) {
        vis[i] = false;
    }

    vis[x] = true;
    q.push(x);
    while(!q.empty()) {
        int node = q.front();
        q.pop();
        for (auto i: graph[node]) {
            if (!vis[i] and rest[node][i]) {
                vis[i] = true;
                next[i] = node;
                if (i != n) {
                    q.push(i);
                }
            }
        }
    }
    return vis[n];
}