Cod sursa(job #3203691)

Utilizator csamoilasamoila ciprian casian csamoila Data 14 februarie 2024 10:43:22
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <bits/stdc++.h>
#define NMAX 1001
#define INF 1e9

using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

int n, m;
int capacity[NMAX][NMAX];
vector<vector<int>> adj;

int bfs(int s, int t, vector<int>& parent) {
    fill(parent.begin(), parent.end(), -1);
    parent[s] = -2;
    queue<int> q;
    q.push(s);

    while (!q.empty()) {
        int cur = q.front();
        q.pop();

        for (int next : adj[cur]) {
            if (parent[next] == -1 && capacity[cur][next]) {
                parent[next] = cur;
                q.push(next);
            }
        }
    }
    if(parent[t] != -1) return 1;
    return 0;
}

int maxflow(int s, int t) {
    int flow = 0;
    vector<int>parent(n+1);
    int new_flow;

    while (bfs(s, t, parent)) {
        for(auto leaf : adj[t]) {
            if(parent[leaf] != -1) {
                int cur_flow = capacity[leaf][t];
                int cur = leaf;
                while(cur != s) {
                    int prev = parent[cur];
                    cur_flow = min(cur_flow, capacity[prev][cur]);
                    cur = prev;
                }
                if(!cur_flow) continue;
                capacity[leaf][t] -= cur_flow;
                capacity[t][leaf] += cur_flow;
                cur = leaf;
                while(cur != s) {
                    int prev = parent[cur];
                    capacity[prev][cur] -= cur_flow;
                    capacity[cur][prev] += cur_flow;
                    cur = prev;
                }
                flow += cur_flow;
            }
        }
    }

    return flow;
}

int main()
{
    fin >> n >> m;
    adj = vector<vector<int>>(n + 1);
    for (int i = 1; i <= m; i++) {
        int a, b, c;
        fin >> a >> b >> c;
        capacity[a][b] = c;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }
    fout << maxflow(1, n);
    return 0;
}