Cod sursa(job #2814424)

Utilizator cont_sa_nu_vada_dumiPopescu Florin cont_sa_nu_vada_dumi Data 8 decembrie 2021 02:23:44
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <bits/stdc++.h>
#define INF INT_MAX / 2
using namespace std;
int n = 5;
vector<vector<int>> capacity;
vector<vector<int>> adj;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int bfs(int s, int t, vector<int>& parent) {
    fill(parent.begin(), parent.end(), -1);
    parent[s] = -2;
    queue<pair<int, int>> q;
    q.push({s, INF});

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

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

    return 0;
}

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

    while (new_flow = bfs(s, t, parent)) {
        flow += new_flow;
        int cur = t;
        while (cur != s) {
            int prev = parent[cur];
            capacity[prev][cur] -= new_flow;
            capacity[cur][prev] += new_flow;
            cur = prev;
        }
    }

    return flow;
}


void resizeVec( std::vector<std::vector<int> > &vec , const unsigned short ROWS , const unsigned short COLUMNS )
{
    vec.resize( ROWS );
    for( auto &it : vec )
    {
        it.resize( COLUMNS );
    }
}

int main(){
    int V, E;
    fin >> V >> E;
    resizeVec(capacity, 1005, 1005);
    resizeVec(adj, 1005, 1005);
    for(int i = 1; i <= E; ++i)
    {
        int src, dst, cap;
        fin >> src >> dst >> cap;
        adj[src].push_back(dst);
        adj[dst].push_back(src);
        capacity[src][dst] = cap;
    }
    fout << maxflow(1, V);
    return 0;
}