Cod sursa(job #3227603)

Utilizator matyaskrizbaiKrizbai Matyas matyaskrizbai Data 2 mai 2024 10:36:12
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

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

long long min(long long a, long long b) {
    return a<b ? a : b;
}

long long bfs(int s, int t, vector<vector<int>> &adj, vector<vector<long long>> &capacity, vector<int> &parent) {
    for(int i=1; i<=t; i++) {
        parent[i]=-1;
    }
    parent[s]=-2;
    queue<pair<int, long long>> q;
    q.push({s, LLONG_MAX});

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

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

    return 0;
}

long long flow(int s, int t, vector<vector<int>> &adj, vector<vector<long long>> &capacity) {
    long long maxflow=0;
    vector<int> parent(t+1);
    long long new_flow;

    while(new_flow=bfs(s, t, adj, capacity, parent)) {
        maxflow+=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 maxflow;
}

int main() {
    int n, m;
    fin >> n >> m;
    vector<vector<int>> adj(n+1);
    vector<vector<long long>> capacity(n+1, vector<long long>(n+1));
    for(int i=0; i<m; i++) {
        int u, v;
        long long cap;
        fin >> u >> v >> cap;
        adj[u].push_back(v);
        adj[v].push_back(u);
        capacity[u][v]=cap;
    }

    fout << flow(1, n, adj, capacity);
    return 0;
}