Cod sursa(job #2939108)

Utilizator Giulian617Buzatu Giulian Giulian617 Data 13 noiembrie 2022 00:08:21
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
//Max Flow Edmonds-Karp
//O(N*M*M)
#include <bits/stdc++.h>
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
const int NMAX=1005,INF=0x3F3F3F3F;
int n,m,x,y,c,new_flow;
struct flux
{
    int flow,capacity;
} graph[NMAX][NMAX];
vector<int>parent;
queue<pair<int,int>>q;
int bfs(int s,int t)
{
    while(!q.empty())///since when we find a path the queue still has some values in it
        q.pop();
    parent.assign(n+1,-1);
    parent[s]=-2;///so that we cannot reach it afterwards
    q.push({s,INF});
    while(!q.empty())
    {
        int node=q.front().first;
        int flow=q.front().second;
        q.pop();
        for(int i=1; i<=n; i++)
            if((graph[node][i].capacity-graph[node][i].flow)>0 && parent[i]==-1)///if I can still push at least one unit of flow and the node is not visited
            {
                int new_flow=min(flow,graph[node][i].capacity-graph[node][i].flow);///second parameter is the number of units of flow I can push through this edge
                parent[i]=node;
                if(i==t)
                    return new_flow;
                q.push({i,new_flow});
            }
    }
    return 0;
}
int max_flow(int s,int t)///source, terminal
{
    int flow=0,new_flow,curr,prev;
    while(1)
    {
        new_flow=bfs(s,t);///this generates a new flow
        if(new_flow==0)
            break;
        flow+=new_flow;
        curr=t;
        while(curr!=s)
        {
            prev=parent[curr];
            graph[prev][curr].flow+=new_flow;///update on the normal edge
            graph[curr][prev].flow-=new_flow;///update on the reverse edge
            curr=prev;
        }
    }
    return flow;
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    f>>n>>m;
    for(int i=1; i<=m; i++)
    {
        f>>x>>y>>c;
        graph[x][y].capacity=c;///graph[x][y].flow=0 already
    }
    g<<max_flow(1,n);///source, terminal
    return 0;
}