Cod sursa(job #3039691)

Utilizator alexmorosanuMorosanu Alexandru alexmorosanu Data 28 martie 2023 19:36:54
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>
#define N 1011
using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");
vector <int> v[N];
int cap[N][N],flow[N][N];
int lvl[N],ef[N],n;
bool bfs()
{
    queue <int> q;
    for(int i=1;i<=n;i++)
        lvl[i]=ef[i]=0;
    q.push(1);
    lvl[1]=1;
    while(!q.empty())
    {
       int x=q.front();
       q.pop();
       for(auto y : v[x])
       {
           if(lvl[y]==0 && cap[x][y]>flow[x][y])
                {
                    lvl[y]=lvl[x]+1;
                    q.push(y);
                }
       }
    }
    return lvl[n]>0;
}
int dfs(int k,int flowu)
{
    if(k==n)
        return flowu;
    for(;ef[k]<v[k].size();ef[k]++)
    {
        int x=v[k][ef[k]];
        if(lvl[x]==lvl[k]+1 && cap[k][x]>flow[k][x])
        {
            int curr_flow=min(flowu,cap[k][x]-flow[k][x]);
            curr_flow=dfs(x,curr_flow);
            if(curr_flow)
            {
                flow[k][x]+=curr_flow;
                flow[x][k]-=curr_flow;
                return curr_flow;
            }
        }
    }
    return 0;
}
int Dinic()
{
    int total_flow=0,new_flow=0;
    while(bfs())
    {
        new_flow=0;
        while(1)
        {
            new_flow=dfs(1,1e9+1);
            if(!new_flow)
                break;
            total_flow+=new_flow;
        }
    }
    return total_flow;
}
int m,x,y,z,i;
int main()
{
    f>>n>>m;
    for(i=1;i<=m;i++)
    {
        f>>x>>y>>z;
        v[x].push_back(y);
        v[y].push_back(x);
        cap[x][y]=z;
    }
    g<<Dinic();
    return 0;
}