Cod sursa(job #2939595)

Utilizator Giulian617Buzatu Giulian Giulian617 Data 13 noiembrie 2022 22:12:55
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.33 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;
struct flux
{
    long long flow,capacity;
} graph[NMAX][NMAX];
vector<int>level,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
}
int dfs(int node,int t,long long cur_flow)
{
    if(node==t)
        return cur_flow;
    for(int& i=skip[node]; i<edges[node].size(); 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 && 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);
            int bottleNeck=dfs(next,t,cur_flow);
            if(bottleNeck>0)
            {
                graph[node][next].flow+=bottleNeck;///update on the normal edge
                graph[next][node].flow-=bottleNeck;///update on the reverse edge
                return bottleNeck;
            }
        }
    }
    return 0;
}
long long maxflow(int s,int t)
{
    long long max_flow=0;
    skip.resize(n+1);
    while(bfs(s,t))
    {
        fill(skip.begin(),skip.end(),0);///for pruning dead ends
        for(int new_flow=dfs(s,t,INF);new_flow!=0;new_flow=dfs(s,t,INF))
            max_flow+=new_flow;
    }
    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;
}