Cod sursa(job #2734894)

Utilizator Chirac_MateiChiriac Matei Chirac_Matei Data 1 aprilie 2021 16:32:45
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.49 kb
#include <bits/stdc++.h>

using namespace std;

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

struct edge
{
    int y;
    long long f, cap;

    edge(int y, long long cap)
    {
        this->y=y;
        this->cap=cap;
        this->f=0;
    }
};
struct dinic
{
    int n,m,s,t;
    vector<edge> e;
    vector<vector<int>> adj;
    vector<int> ptr;
    vector<int> lvl;

    queue<int> q;

    dinic(int n, int s, int t)
    {
        this->n=n;
        m=0;

        this->s=s;
        this->t=t;

        adj.resize(n+1);
        ptr.resize(n+1);
        lvl.resize(n+1);
    }

    void add_edge(int x, int y, long long cap)
    {
        e.push_back(edge(y, cap));
        adj[x].push_back(m);

        e.push_back(edge(x, 0));
        adj[y].push_back(m+1);

        m+=2;
    }

    bool bfs()
    {
        q.push(s);

        while(!q.empty())
        {
            int p=q.front();
            q.pop();

            for(int id : adj[p])
            {
                if(e[id].cap - e[id].f == 0)
                    continue;

                if(lvl[e[id].y] != -1)
                    continue;

                lvl[e[id].y] = lvl[p]+1;
                q.push(e[id].y);
            }
        }

        return lvl[t] != -1;
    }

    long long dfs(int p, long long pushed)
    {
        if(!pushed)
            return 0;

        if(p==t)
            return pushed;

        for(int &i=ptr[p]; i < (int)adj[p].size(); i++)
        {
            int id=adj[p][i];

            if(lvl[e[id].y] != lvl[p]+1)
                continue;

            long long npushed=dfs(e[id].y, min(pushed, e[id].cap - e[id].f));

            if(!npushed)
                continue;

            e[id].f+=npushed;
            e[id^1].f-=npushed;

            return npushed;
        }

        return 0;
    }

    long long flow()
    {
        long long ans=0;

        while(true)
        {
            fill(lvl.begin(), lvl.end(), -1);
            lvl[s]=0;

            if(!bfs())
                break;

            fill(ptr.begin(), ptr.end(), 0);
            while(long long pushed=dfs(s, 1e18))
                ans+=pushed;
        }

        return ans;
    }
};
int main()
{
    int n,m,x,y;
    long long cap;

    fin>>n>>m;
    dinic g=dinic(n, 1, n);

    while(m)
    {
        m--;
        fin>>x>>y>>cap;
        g.add_edge(x, y, cap);
    }

    fout<<g.flow();
    return 0;
}