Cod sursa(job #2939565)

Utilizator Giulian617Buzatu Giulian Giulian617 Data 13 noiembrie 2022 21:52:12
Problema Flux maxim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.66 kb
///Max Flow Dinic's Algorithm
///O(N*N*M) on normal graphs
///O(sqrt(N)*M) on bipartite graphs
#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>level,parent,skip,edges[NMAX];
bool bfs(int s,int t)
{
    level.assign(n+1,-1);
    level[s]=0;
    queue<int>q;
    q.push(s);
    while(!q.empty())
    {
        int node=q.front();
        q.pop();
        for(int next:edges[node])
            if(graph[node][next].capacity-graph[node][next].flow>0 && level[next]==-1)///if I can still push flow and the node is not visited
            {
                level[next]=level[node]+1;
                q.push(next);
            }
    }
    return level[t]!=-1;///if t was visited it will return 1,otherwise 0
}
void dfs(int node,int t,int cur_flow)
{
    for(int i=0; i<edges[node].size() && t>0; i++)///thanks to the reference, the skip vector will also change
    {
        int next=edges[node][i];
        if(graph[node][next].capacity-graph[node][next].flow>0 && parent[next]==-1 && level[node]+1==level[next])///if I can still push flow and the node is not visited and we only go forward
        {
            cur_flow=min(cur_flow,graph[node][next].capacity-graph[node][next].flow);
            parent[next]=node;
            if(next==t)
            {
                new_flow=cur_flow;
                t=-1;///we should not reach it after finding a path
            }
            dfs(next,t,cur_flow);
        }
    }
}
int maxflow(int s,int t)
{
    int max_flow=0,curr,prev;
    parent.resize(n+1);
    //skip.resize(n+1);
    while(bfs(s,t))
    {
        fill(parent.begin(),parent.end(),-1);
        parent[s]=-2;
        //fill(skip.begin(),skip.end(),0);
        while(1)
        {
            new_flow=0;
            dfs(s,t,INF);
            if(new_flow==0)
                break;
            max_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 max_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
        edges[x].push_back(y);
    }
    g<<maxflow(1,n);///source, terminal
    return 0;
}