Cod sursa(job #2760549)

Utilizator SochuDarabaneanu Liviu Eugen Sochu Data 27 iunie 2021 17:36:58
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.71 kb
#include <bits/stdc++.h>
#define FastIO ios_base::sync_with_stdio(false) , cin.tie(0) , cout.tie(0)
#define FILES freopen("maxflow.in" , "r" , stdin) , freopen("maxflow.out" , "w" , stdout)
#define ll long long
#define ull unsigned long long
#define ld long double
#define eb emplace_back
#define pb push_back
#define qwerty1 first
#define qwerty2 second
#define qwerty3 -> first
#define qwerty4 -> second
#define umap unordered_map
#define uset unordered_set
#define pii pair < int , int >
#define pq priority_queue
#define dbg(x) cerr << #x << ": " << x << '\n'
#define Min(a , b) (a > b ? b : a)

namespace FastRead
{
    char __buff[5000];int __lg = 0 , __p = 0;
    char nc()
    {
        if(__lg == __p){__lg = fread(__buff , 1 , 5000 , stdin);__p = 0;if(!__lg) return EOF;}
        return __buff[__p++];
    }
    template<class T>void read(T&__x)
    {
        T __sgn = 1; char __c;while(!isdigit(__c = nc()))if(__c == '-')__sgn = -1;
        __x = __c - '0';while(isdigit(__c = nc()))__x = __x * 10 + __c - '0';__x *= __sgn;
    }
}

using namespace FastRead;
using namespace std;

const int N = 1e3 + 10;

int n , m , x , y , c;
int capacity[N][N] , parent[N];
vector < int > G[N];

int bfs(int source , int sink)
{
    memset(parent , 0 , sizeof(parent));
    parent[source] = -1;

    queue < int > q;
    q.push(source);

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

        if(x == sink) continue;

        for(auto i : G[x])
        {
            if(!capacity[x][i] || parent[i])
                continue;

            parent[i] = x;
            q.push(i);
        }
    }

    return parent[sink] != 0;
}

int max_flow(int source , int sink)
{
    int flow = 0;

    while(bfs(source , sink))
        for(auto i : G[sink])
        {
            if(!capacity[i][sink] || !parent[i]) continue;

            parent[sink] = i;

            int new_flow = INT_MAX;

            for(int cur = sink ; cur != source ; cur = parent[cur])
                new_flow = min(new_flow , capacity[ parent[cur] ][cur]);

            for(int cur = sink ; cur != source ; cur = parent[cur])
            {
                capacity[ parent[cur] ][cur] -= new_flow;
                capacity[cur][ parent[cur] ] += new_flow;
            }

            flow += new_flow;
        }

    return flow;
}

signed main()
{
	#ifndef ONLINE_JUDGE
		FastIO , FILES;
	#endif

    //cin >> n >> m;
    read(n) , read(m);

    for(int i = 1 ; i <= m ; i++)
    {
        read(x) , read(y) , read(c);//cin >> x >> y >> c;
        capacity[x][y] = c;

        G[x].pb(y);
        G[y].pb(x);
    }

    cout << max_flow(1 , n);

    return 0;
}